简体   繁体   English

在React Router中以编程方式在哪里重新路由?

[英]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.

相关问题 在我的父组件中使用 React Router 登录后如何重新路由? - How can I re-route after a sign-in using React Router in my parent component? React Router显示为未定义,我如何不使用window.location重新路由到某个页面 - React router shows up as undefined, how would I re-route to a certain page without using window.location 重新路由未使用React登录的用户的干净方法? - Clean way to re-route user that isn't logged in with React? 如何重新路由 React-Admin url - How to re-route a React-Admin url 路由问题:尝试重新路由时未定义 this.context.router - Routing issue: this.context.router not defined when trying to re-route 使用React Router 4以编程方式通过路由传递数据 - Pass data programatically on route change with React router 4 如何在 React/Gatsby 中将标题菜单项重新路由到 URL 而不是内部文件? - How do I re-route header menu items to a URL instead of internal file in React/Gatsby? React-Router - 路由更改时的路由重新渲染组件 - React-Router - Route re-rendering component on route change React-Router:以编程方式从根元素路由到路由 - React-Router: Programatically routing to a route from the root element 如何使用React Router 5以编程方式向上升级路由层次结构? - How to programatically go one level up of the route hierarchy with React router 5?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM