React Router中同一组件的多个路径名称

217

我正在为三个不同的路由使用相同的组件:

<Router>
    <Route path="/home" component={Home} />
    <Route path="/users" component={Home} />
    <Route path="/widgets" component={Home} />
</Router>

有没有办法将它们合并成这样:

<Router>
    <Route path=["/home", "/users", "/widgets"] component={Home} />
</Router>

1
我的回答有帮助吗? - Ben Smith
12个回答

0
这是一个小函数,可以将带有“paths”属性的自定义路由转换为多个标准路由,以便支持react-router v6,并使用“path”属性:
const normalizeRoutes = (routes) =>
  routes.reduce((acc, curr) => {
    const newRoute = curr.children
      ? { ...curr, children: normalizeRoutes(curr.children) }
      : curr;
    if (newRoute.paths) {
      return [
        ...acc,
        ...newRoute.paths.map((path) => {
          const { paths, ...rest } = newRoute;
          return { ...rest, path };
        })
      ];
    }
    return [...acc, newRoute];
  }, []);

0

react-router-dom 不再支持在路径中使用正则表达式,一个替代方法是将组件保存在变量中,并将其用作多个路由的组件。

let home= <Home />

<Route path={"/home" | "/users" | "/widgets"} component={Home} />

return <Routes>
        <Route path="/home" element={home} />
        <Route path="/users" element={home} />
        <Route path="/widgets" element={home} />
    </Routes>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接