reactjsreact-routerhrefpathnamelocation-href

Duplicate pathname issue in useLocation


I'm making a web with react and react router.

The problem is, the pathname in useLocation() has a record of the previous page and a record of the current page.

For example, '/' on the home screen and the '/business' page on another page are contrasted together.

Also, if you refresh on the /business page and go to ‘/info’, ‘/business’ and ‘/info’ appear together.

If you look at the picture I posted above, whenever a scroll event occurs, I try to determine if the pathname (the same is the url variable) variable is ‘/’ and write logic according to the boolean value.

However, there are cases where there are two executions in the console, in the statement, with the old pathname and the current pathname.

If only url or url is taken to the console, the current result value is displayed, but the history of the previous page is also actually brought if it is suggested in the scroll event of the window.

Does anyone know a solution for this? enter image description here


Solution

  • You may be needing the exact keyword:

    When true, the active class/style will only be applied if the location is matched exactly.

    <Switch>
      <Route exact path="/"><Home/></Route>
      <Route exact path="/accounts/login"><Login/></Route>
      <Route exact path="/accounts/profile"><Profile/></Route>
    </Switch>
    

    It may be because you have an '/' route defined so that React Router couldn't interpret the URLs accurately.

    Yes, applying the prop to every Route may be overkill, but it guarantees no room for bugs.