https://reacttraining.com/react-router/web/example/auth-workflow
他们的PrivateRoute组件如下所示:
const PrivateRoute = ({ component: Component,...rest }) => ( <Route {...rest} render={props => ( fakeAuth.isAuthenticated ? ( <Component {...props}/> ) : ( <Redirect to={{ pathname: '/login',state: { from: props.location } }}/> ) )}/> )
但是,因为我已将其合并到Redux应用程序中,所以我不得不稍微调整一下PrivateRoute,以便我可以访问redux存储以及路径Props:
const PrivateRouteComponent = (props) => ( <Route {...props.routeProps} render={() => ( props.logged_in ? ( <div>{props.children}</div> ) : ( <Redirect to={{ pathname: '/login',state: { from: props.location } }} /> ) )} /> ); const mapStateToProps = (state,ownProps) => { return { logged_in: state.auth.logged_in,location: ownProps.path,routeProps: { exact: ownProps.exact,path: ownProps.path } }; }; const PrivateRoute = connect(mapStateToProps,null)(PrivateRouteComponent); export default PrivateRoute
每当我没有登录并点击PrivateRoute时,我都被正确地重定向到/ login。但是,例如登录并使用< Redirect ... />或点击任何< Link ...>对于PrivateRoute,URI会更新,但视图不会更新。它保留在同一个组件上。
我究竟做错了什么?
只是为了完成图片,在应用程序的index.js中有一些不相关的东西,路由设置如下:
ReactDOM.render( <Provider store={store}> <App> <Router> <div> <PrivateRoute exact path="/"><Home /></PrivateRoute> // ... other private routes <Route path="/login" component={Login} /> </div> </Router> </App> </Provider>,document.getElementById('root') );