React Router 4.x - PrivateRoute 在连接到 Redux 后不起作用 [英] React Router 4.x - PrivateRoute not working after connecting to Redux
问题描述
PrivateRoute 在示例中可用 https://reacttraining.com/react-router/web/example/auth-workflow 与 Redux 连接后无法正常工作.
PrivateRoute available in Example https://reacttraining.com/react-router/web/example/auth-workflow is not working after connecting with Redux.
我的 PrivateRoute 看起来与原始版本几乎相同,但仅连接到 Redux 并在原始示例中使用它而不是 fakeAuth.
My PrivateRoute look almost same to the original version but only connected to Redux and used it instead of fakeAuth in the original example.
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
<Route
{...rest}
render={props =>
auth.isAuthenticated
? <Component {...props} />
: <Redirect to={{ pathname: "/login" }} />}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired,
component: PropTypes.func.isRequired
}
const mapStateToProps = (state, ownProps) => {
return {
auth: state.auth
}
};
export default connect(mapStateToProps)(PrivateRoute);
使用和结果:-
- 不工作但想要&期待工作
<PrivateRoute path="/member" component={MemberPage} auth={auth}/>
<PrivateRoute path="/member" component={MemberPage} anyprop={{a:1}}/>
推荐答案
补充 @Tharaka 答案,您可以将 {pure: false}
传递给 connect
方法,如中所述react-redux 故障排除部分.
Complementary to @Tharaka answer you can pass {pure: false}
to connect
method as described in react-redux troubleshooting section.
React-redux 对 shouldComponentUpdate
钩子中的 props 进行浅层比较,以避免不必要的重新渲染.如果上下文道具发生变化(react-router),它不会检查它,并且假设没有任何变化.
React-redux makes shallow comparison of props in shouldComponentUpdate
hook to avoid unnecessary re-renders. If context props changed (react-router) it doesn’t check for that and it assumes nothing has changed.
{ pure:false }
只是禁用这种浅比较.
{ pure:false }
simply disables this shallow comparison.
这篇关于React Router 4.x - PrivateRoute 在连接到 Redux 后不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!