[英]Where to programatically re-route in React Router?
Suppose I have some component that is connected to react router and redux. 假设我有一些组件已连接以响应路由器和redux。 I want the component to automatically re-direct to another route when the state "isLoggedIn" becomes false.
我希望组件在状态“ isLoggedIn”变为false时自动重定向到另一条路由。 This is what I have so far:
这是我到目前为止的内容:
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>;
}
}
))
Current the below works but I see an error in the console: 目前以下工作,但我在控制台中看到错误:
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`.
If I moved this logic to componentWillMount
, it obviously only runs once. 如果我将此逻辑移到
componentWillMount
,则显然只运行一次。
What is the right way to set something like this up? 设置类似这样的正确方法是什么? I understand I could possibly amend the
logOut
method to do the router.push
but that doesn't feel ideal. 我知道我可以修改
logOut
方法来做router.push
但这并不理想。 I'd prefer the component to handle that based on the state. 我希望组件能够根据状态进行处理。
我认为您可以尝试使用componentWillUpdate(nextProps, nextState)
生命周期方法以查看其是否已登录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.