2017-07-30 85 views
1

我使用的是the next (5.0.0) version react-router-redux,它与react-router 4.x兼容。如何避免重定向两次(react-router-redux)?

我的应用有两个页面/login/home

如果用户访问不存在的页面,我试图将页面重定向到/login。这是我的代码

import { Route, Redirect } from 'react-router-dom'; 
import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux'; 

ReactDOM.render(
    <Provider store={store}> 
    <ConnectedRouter history={history}> 
     <div> 
     <Route path="/login" render={() => (
      isSignedIn ? <Redirect to="/home" /> : <Login /> 
     )}/> 

     <Route path="/home" component={Home} /> 

     <Redirect to="/login" /> 
     </div> 
    </ConnectedRouter> 
    </Provider>, 
    document.getElementById('root') 
); 

如果我删除<Redirect to="/login" />如果用户已登录,他打开/home页面时,应用程序将访问主页直接,这是很好的。

但是,当用户打开页面/home时,应用程序将首先重定向到/login,然后返回到/home

我该如何避免这种重定向两次?由于

+0

为什么不配置家庭路由,然后重定向到登录是用户没有从家庭组件登录 –

+0

您好@ShubhamKhatri,我没有得到它,你能解释更多?谢谢 –

+0

看到这个问题检查登录在主页https://stackoverflow.com/questions/44127739/programatically-routing-based-on-a-condition-with-react-router/44128108#44128108和重定向 而我意思是你可以有一个类似于'' –

回答

2

利用Switch,使得第一匹配的路由被渲染,并没有别的

import {Switch} from 'react-router'; 

ReactDOM.render(
    <Provider store={store}> 
    <ConnectedRouter history={history}> 
     <Switch> 
     <Route path="/login" render={() => (
      isSignedIn ? <Redirect to="/home" /> : <Login /> 
     )}/> 

     <Route path="/home" component={Home} /> 

     <Redirect to="/login" /> 
     </Switch> 
    </ConnectedRouter> 
    </Provider>, 
    document.getElementById('root') 
); 

你的情况会发生什么事是,即使/home匹配,则也将执行Redirect

+0

感谢您提醒''! –

+0

正如我在我的评论中所说的,您可以保持重定向的逻辑以在Home组件中登录。请参阅https://stackoverflow.com/questions/44127739/programatically-routing-based-on-a-condition-with-react-router/44128108#44128108 –