【问题标题】:React-Router: How to redirect Route to another url conditionally?React-Router:如何有条件地将 Route 重定向到另一个 url?
【发布时间】:2020-06-14 01:10:52
【问题描述】:

使用 React Route,但我遇到了这个问题:在某些情况下,我需要应用程序加载与实际不同的 url。这是我所做的:

class Application extends React.Component {
  render() {
    const { history } = this.props;
    let loadExact = true;

    if (my_condition === true) {
      loadExact = false;
    }

    return (
      <Dashboard history={history}>
        <Switch>
          {
           loadExact ? <Route exact path="/app" component={MainPage} /> : 
           (
              <Redirect to={{
                  pathname: "/app/theotherpage",
                  state: {from: history}
                }} 
              />
           )
          }

          <Route path="/app/theotherpage" component={TheOtherPage} />

          <Route component={NotFound} />
        </Switch>
      </Dashboard>
    );
  }
}

我需要的是如果loadExactfalse 然后重定向到/app/theotherpage 并因此加载它而不是/app。这样它就进入了一个完全空白的页面,它告诉我:

无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。

我该如何解决这个问题?

【问题讨论】:

  • 尝试使用history.push()。它还说您没有进行清理

标签: reactjs redirect react-router


【解决方案1】:

有两种方法:

  1. 通过&lt;Switch&gt;之外的重定向

    if (my_condition === true) { loadExact = 假; 负载补偿 = ; }

    return (
      <Dashboard history={history}>
       {loadComp}
        <Switch>
          <Route exact path="/app" component={MainPage} />
          <Route path="/app/theotherpage" component={TheOtherPage} />
          <Route component={NotFound} />
        </Switch>
      </Dashboard>
    );
    

    } }

  2. 通过history.push

    `class Application 扩展 React.Component { 使成为() { 常量 { 历史 } = this.props; 让 loadExact = true;

    if (my_condition === true) {
      loadExact = false;
      this.props.history.push('/app/theotherpage');
    }
    
    return (
      <Dashboard history={history}>
        <Switch>
          <Route exact path="/app" component={MainPage} />
          <Route path="/app/theotherpage" component={TheOtherPage} />
          <Route component={NotFound} />
        </Switch>
      </Dashboard>
    );
    

    } }`

【讨论】:

  • 您的第二个选项根本不起作用。但是第一个我看不懂,你能重新解释一下吗?
【解决方案2】:

正如Prakash Reddy Potlapadu 建议的那样,我使用了history.push。代码如下:

componentDidMount() {
   if (my_condition) {
      history.push("/app/theotherpage");
   }
}

就是这样。像魅力一样工作。

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2016-04-16
    • 2016-05-24
    • 2022-01-24
    • 2019-07-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多