React Router always redirect me to a different url

守給你的承諾、 提交于 2019-12-06 06:03:41

The problem is that even if you enter the URL with query this URL matches Redirect path (since it's just / any URL matches this pattern) so the redirection to /bugs occurs. You have to use Switch (remember to import it) to render only the first <Route> or <Redirect> that matches the URL:

<Router>
     <Switch>
        <Route path='/bugs' component={BugList}/>
        <Redirect from='/' to="/bugs" />
        ...
   </Switch>
</Router>

The problem occured only on page load and not on re-entering the URL because your routing is based on hashes and the browser doesn't reload page when only hash part changes.
Please note that Redirect component in React-Router v4 performs redirection only when it's rendered - it doesn't set up permanent redirection rule so in your case redirection works only on page load. If you'd like your app to always redirect given URL you'd have to define Route for URL you'd like to redirect from and render Redirect:

<Route path='/oldUrl' render={() => (
    <Redirect to="newUrl" />
)}/>

Furthermore, React-Router v4 is quite different from v3 so I don't recommend using v3 tutorials - it doesn't make sense.

Building on what Bartek said: if you use Switch, it will go directional from top to bottom and render the first hit, since you moved your redirect to the first position it will always hit that first and then not go to the other routes. Which is why your Switch should look like this imho (untested):

<Router>
    <Switch>
        <Route path='/bugs' component={BugList}/>
        <Route path='/bug/:id' component={BugEdit}/>
        <Redirect from='/' to="/bugs" />
        <Route path="*" component={NoMatch} />
    </Switch>
</Router>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!