我已经稍微调整了私有路由的 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')
);