首页 > 解决方案 > 什么时候是使用 React Router Replace(componentDidMount?) 的好时机

问题描述

我有一个组件,如果有人复制 url 并将其分页到新选项卡中,则会崩溃,因为它缺少上一步所需的数据。

我想将他们重定向到其他页面并将其从他们的“返回”历史记录中删除。所以我在考虑使用“替换”

我一直在componentDidMount上这样做,但注意到一切似乎都运行了两次。

// Page1Component
    componentDidMount(){


        if(true){
          const { replace } = props.routingStore;
          const params = props.match.params;

          replace('/members/home')
        }
      }

所以当上面的代码被命中时,这就是发生的事情

  1. Page1Component componentDidMount 加载
  2. HomeComponent componentDidMount 加载
  3. Page1Component componentDidMount 再次加载
  4. HomeComponent componentDidMount 加载

标签: reactjsreact-router

解决方案


您可以直接在方法中使用Redirectrender组件:

if(...) {
  return <Redirect to="/members/home" push={false}/>;
}

请注意, usingpush={false}将替换当前条目到历史记录


推荐阅读