reactjs – React路由器私有路由/重定向无法正常工作

前端之家收集整理的这篇文章主要介绍了reactjs – React路由器私有路由/重定向无法正常工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我稍微调整了React Router示例,让私有路由与Redux一起玩得很好,但在链接重定向到其他“页面”时没有呈现任何组件。这个例子可以在这里找到:

https://reacttraining.com/react-router/web/example/auth-workflow

他们的PrivateRoute组件如下所示:

  1. const PrivateRoute = ({ component: Component,...rest }) => (
  2. <Route {...rest} render={props => (
  3. fakeAuth.isAuthenticated ? (
  4. <Component {...props}/>
  5. ) : (
  6. <Redirect to={{
  7. pathname: '/login',state: { from: props.location }
  8. }}/>
  9. )
  10. )}/>
  11. )

但是,因为我已将其合并到Redux应用程序中,所以我不得不稍微调整一下PrivateRoute,以便我可以访问redux存储以及路径Props:

  1. const PrivateRouteComponent = (props) => (
  2. <Route {...props.routeProps} render={() => (
  3. props.logged_in ? (
  4. <div>{props.children}</div>
  5. ) : (
  6. <Redirect to={{
  7. pathname: '/login',state: { from: props.location }
  8. }} /> )
  9. )} />
  10. );
  11.  
  12. const mapStateToProps = (state,ownProps) => {
  13. return {
  14. logged_in: state.auth.logged_in,location: ownProps.path,routeProps: {
  15. exact: ownProps.exact,path: ownProps.path
  16. }
  17. };
  18. };
  19.  
  20. const PrivateRoute = connect(mapStateToProps,null)(PrivateRouteComponent);
  21. export default PrivateRoute

每当我没有登录并点击PrivateRoute时,我都被正确地重定向到/ login。但是,例如登录并使用< Redirect ... />或点击任何< Link ...>对于PrivateRoute,URI会更新,但视图不会更新。它保留在同一个组件上。

我究竟做错了什么?

只是为了完成图片,在应用程序的index.js中有一些不相关的东西,路由设置如下:

  1. ReactDOM.render(
  2. <Provider store={store}>
  3. <App>
  4. <Router>
  5. <div>
  6. <PrivateRoute exact path="/"><Home /></PrivateRoute>
  7. // ... other private routes
  8. <Route path="/login" component={Login} />
  9. </div>
  10. </Router>
  11. </App>
  12. </Provider>,document.getElementById('root')
  13. );
您需要使用< Switch>包裹您的路线标签
  1. ReactDOM.render(
  2. <Provider store={store}>
  3. <App>
  4. <Router>
  5. <div>
  6. <Switch>
  7. <PrivateRoute exact path="/"><Home /></PrivateRoute>
  8. // ... other private routes
  9. <Route path="/login" component={Login} />
  10. </Switch>
  11. </div>
  12. </Router>
  13. </App>
  14. </Provider>,document.getElementById('root'));

猜你在找的React相关文章