0
假设我有一些连接到路由器和REDX的组件。当状态“isLoggedIn”变为false时,我希望组件自动重定向到另一个路由。这是我到目前为止有:在React路由器中以编程方式重新路由的地方?
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>;
}
}
))
当前下面的作品,但我看到一个错误在控制台:
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`.
如果我搬到这个逻辑componentWillMount
,它显然只运行一次。
什么是正确的方式来设置这样的事情?我知道我可以修改logOut
方法来执行router.push
,但这并不理想。我更喜欢组件来处理基于状态的组件。