Reactjs 在React路由器中,在何处以编程方式重新路由?
假设我有一些组件连接到react路由器和redux。我希望组件在状态“isLoggedIn”变为false时自动重新定向到另一个路由。这就是我到目前为止所做的:Reactjs 在React路由器中,在何处以编程方式重新路由?,reactjs,redux,react-router,react-redux,Reactjs,Redux,React Router,React Redux,假设我有一些组件连接到react路由器和redux。我希望组件在状态“isLoggedIn”变为false时自动重新定向到另一个路由。这就是我到目前为止所做的: withRouter(connect( state => ({ isLoggedIn: selectors.getIsLoggedIn(state), }) )( class AdminGate extends React.Component { render() {
withRouter(connect(
state => ({
isLoggedIn: selectors.getIsLoggedIn(state),
})
)(
class AdminGate extends React.Component {
render() {
const { isLoggedIn, router, ...restProps } = this.props;
if (!isLoggedIn) {
router.push('/');
}
return isLoggedIn ? <InnerComponent {...restProps} /> : <div>Prohibited</div>;
}
}
))
如果我将此逻辑移动到组件willmount
,它显然只运行一次
什么是正确的方式来设置这样的事情?我知道我可能会修改
注销
方法来执行路由器。推送
,但这并不理想。我希望组件根据状态来处理该问题。我认为您可以尝试使用componentWillUpdate(nextProps,nextState)
生命周期方法,以查看它是否已登录。我认为您可以尝试使用componentWillUpdate(nextProps,nextState)
lifecycle方法,以查看是否已登录
warning.js:44 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.