首页 > 解决方案 > React Router 不会为每条路径重定向

问题描述

我有一个嵌套的反应路由器组件。每当路由匹配 /home/:id 时,就会调用 home 组件,该组件具有更多路由,例如 /home/store。

现在,每当我输入/home/ANY时,它都会成功重定向到/home/store。但它不适用于/home/store/ANY并且我得到一个空页面。
我希望/home/store/ANY旁边的任何内容都应该重定向到/home/store

家庭组件

<Switch>
          
<Route path='/home/store' exact>
  <Store />
</Route>
          
<Route
  path='*'
 render={({ location }) => redirectWrapper('/home/store', location)}
/>

</Switch>

重定向包装函数

export function redirectWrapper(path, location) {
  return (
    <Redirect to={{ pathname: path, state: { from: location } }}></Redirect>
  );
}

标签: reactjsreact-routerreact-router-dom

解决方案


Ciao,你为什么不尝试在 Home 组件中添加一个 Route,例如:

<Switch>
      
  <Route path='/home/store' exact>
     <Store />
  </Route>
      
  <Route
    path='*'
    render={({ location }) => redirectWrapper('/home/store', location)}
  />

  <Route 
    path='/home/store/(.*)'
    render={({ location }) => redirectWrapper('/home/store', location)}
  />

</Switch>

推荐阅读