【发布时间】:2017-09-17 03:29:08
【问题描述】:
我稍微调整了 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 会更新,但视图不会。它停留在同一个组件上。
我做错了什么?
补图,在app的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')
);
【问题讨论】:
标签: reactjs redux react-router react-redux