React-router-dom - 警告:您试图重定向到您当前所在的同一路线

React-router-dom - Warning: You tried to redirect to the same route you're currently on

我正在构建一个带有动画路线转换的 React 应用程序。一切似乎都正常,但控制台不断显示标题警告。 下面是我的路线渲染函数:

render() {
  return (
    <main>
      <ReactCSSTransitionGroup
        transitionName="app"
        transitionEnterTimeout={600}
        transitionLeaveTimeout={600}
      >
        <Switch key={location.pathname} location={location}>
          <Route path="/route1" component={Route1} />
          <Route path="/route2" component={Route2} />
          <Route path="/route3" component={Route3} />
          <Redirect to="/route1" />
        </Switch>
      </ReactCSSTransitionGroup>
    </main>
  );
}

我有 3 条路线,其他所有路线都应重定向到 /route1。如果我在url栏中手动输入/route4,就会出现警告。

如果我删除 ReactCSSTransitionGroup,警告就会消失。

render() {
  return (
    <main>
      <Switch key={location.pathname} location={location}>
        <Route path="/route1" component={Route1} />
        <Route path="/route2" component={Route2} />
        <Route path="/route3" component={Route3} />
        <Redirect to="/route1" />
      </Switch>
    </main>
  );
}

由于该应用程序可以运行,所以这没什么大不了的。但我更喜欢在我的应用程序中没有警告,我想保留过渡。

尝试将 <Redirect /> 放在 <Route /> 上方。

render() {
  return (
    <main>
      <ReactCSSTransitionGroup
        transitionName="app"
        transitionEnterTimeout={600}
        transitionLeaveTimeout={600}
      >
        <Switch key={location.pathname} location={location}>
          <Redirect to="/route1" />
          <Route path="/route1" component={Route1} />
          <Route path="/route2" component={Route2} />
          <Route path="/route3" component={Route3} />
        </Switch>
      </ReactCSSTransitionGroup>
    </main>
  );
}

没有 path 道具的路线将始终呈现。

因此,如果您想将 Route1 指定为包罗万象的组件,只需删除它的 path 属性即可。

当然Switch会显示匹配的第一条路线,所以catch-all需要是最后一条路线。

<Switch key={location.pathname} location={location}>
    <Route path="/route2" component={Route2} />
    <Route path="/route3" component={Route3} />
    <Route component={Route1} />
</Switch>