首页 > 解决方案 > Reactjs重定向路由不起作用但url更新

问题描述

我需要默认从父路径重定向到子路径。但路线正在更新。但该组件未呈现。

这是我的路线详情:

懒惰的部分:

const UK = React.lazy(() => import("./components/page-projects/project-uk/project-uk.component"));
const FR = React.lazy(() => import("./components/page-projects/project-france/project-france.component"));
const LT = React.lazy(() => import("./components/page-projects/project-lithuania/project-lithuania.component"));

路线路径:

 <Redirect from="/projects" to="/projects/united-kingdom">
    <Route path="/projects/united-kingdom" component={UK}></Route>
    <Route path="/projects/france" component={FR}></Route>
    <Route path="/projects/lithuania" component={LT}></Route>
 </Redirect>

这里有什么问题?有人帮我吗?我的版本react is 17x

标签: reactjsreact-routerreact-router-dom

解决方案


<Switch />组件将仅渲染与路径匹配的第一个路由。一旦找到与路径匹配的第一条路由,它就不会寻找任何其他匹配项。不仅如此,它还允许嵌套路由正常工作,因为这Redirect是一个你应该包裹在Switch组件下的路由

<Switch>
  <Redirect from="/projects" to="/projects/united-kingdom" />
  <Route path="/projects/united-kingdom" component={UK} />
  <Route path="/projects/france" component={FR} />
  <Route path="/projects/lithuania" component={LT} />
</Switch>

推荐阅读