reactjs – React路由器私有路由/重定向无法正常工作
发布时间:2020-12-15 20:55:48 所属栏目:百科 来源:网络整理
导读:我稍微调整了React Router示例,让私有路由与Redux一起玩得很好,但在链接或重定向到其他“页面”时没有呈现任何组件。这个例子可以在这里找到: https://reacttraining.com/react-router/web/example/auth-workflow 他们的PrivateRoute组件如下所示: const
我稍微调整了React Router示例,让私有路由与Redux一起玩得很好,但在链接或重定向到其他“页面”时没有呈现任何组件。这个例子可以在这里找到:
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') );
您需要使用< Switch>包裹您的路线标签
ReactDOM.render( <Provider store={store}> <App> <Router> <div> <Switch> <PrivateRoute exact path="/"><Home /></PrivateRoute> // ... other private routes <Route path="/login" component={Login} /> </Switch> </div> </Router> </App> </Provider>,document.getElementById('root')); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |