【问题标题】:React router Redirect does not work when route comes from another component当路由来自另一个组件时,React路由器重定向不起作用
【发布时间】:2020-02-11 07:33:49
【问题描述】:

在应用程序中创建路由,我注意到如果之前渲染了带有路​​由的组件,重定向不起作用,我想知道为什么。

const TestRoute = () => {
  return (
      <Route exact path="/d" component={D} />
  );
};

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={A} />
        <Route exact path="/b" component={B} />
        <Route exact path="/c" component={C} />
        <TestRoute />
        <Redirect to="/c" />
      </Switch>
    </Router>
  );
}

如果我删除 TestRoute 重定向工作,我尝试在 TestRoute 中添加 Switch 组件,但它也不起作用。

https://codesandbox.io/s/react-router-switch-es8wt

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    react-router-dom docs 开始,只有RouteRedirectSwitch 组件的有效子级。

    但是

    你可以使用一个函数来返回更多的路由来渲染

    const testRoute = () => <Route exact path="/d" component={D} />;
    
    const RouterApp = () => {
      return (
        <Router>
          <Switch>
            <Route exact path="/a" component={A} />
            <Route exact path="/b" component={B} />
            <Route exact path="/c" component={C} />
            {testRoute()}
            <Redirect to="/c" />
          </Switch>
        </Router>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2020-02-05
      • 2019-01-19
      • 2016-11-27
      相关资源
      最近更新 更多