在 React Router 中以编程方式重新路由的位置?

Where to programatically re-route in React Router?

假设我有一些连接到 React 路由器和 Redux 的组件。我希望组件在状态 "isLoggedIn" 变为假时自动重定向到另一条路线。这是我目前所拥有的:

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 但这感觉并不理想。我更希望组件根据状态来处理。

我想你可以尝试使用 componentWillUpdate(nextProps, nextState) 生命周期方法来查看它是否已登录。