React Router - 嵌套的<Switch>组件是反模式的吗?

che*_*pus 8 react-router react-router-v4 react-router-dom

来自React Router的文档:

a的所有孩子<Switch>应该是<Route><Redirect>元素.只会呈现与当前位置匹配的第一个子项.

尽管如此,<Switch>允许使用嵌套语句.我用这个模式来分解大量的<Routes>:

<Switch>
  <Route path="/foo" component={FooRouter} />
  <Route path="/bar" component={BarRouter} />
  <Route path="/baz" component={BazRouter} />
</Switch>

...

const FooRouter = () => (
  <Switch>
    <Route exact path="/foo/:id" component={ViewFoo} />
    <Route exact path="/foo/new" component={NewFoo} />
  </Switch>
)

const BarRouter = () => (
  <Switch>
    <Route exact path="/bar/new" component={NewBar} />
  </Switch>
)

....
Run Code Online (Sandbox Code Playgroud)

好奇是否有更好的方法来分解大量的路由,是否<Switch>应该避免使用嵌套语句?

小智 3

当你有很多嵌套路由时,你可以很好地解决它,你可以将它们插入应用程序并创建动态路由,但很快react-router-dom v6将发布一个巨大的升级,其中之一是useRoutes,它可以让你配置你的路线是这样的:

let element = useRoutes([
    // A route object has the same properties as a <Route>
    // element. The `children` is just an array of child routes.
    { path: '/', element: <Home /> },
    {
      path: 'users',
      element: <Users />,
      children: [
        { path: '/', element: <UsersIndex /> },
        { path: ':id', element: <UserProfile /> },
        { path: 'me', element: <OwnUserProfile /> },
      ]
    }
  ]);
Run Code Online (Sandbox Code Playgroud)

React-router-dom v6 简介他们有一些很酷的新功能,值得一看,其中之一就是用女巫替换 可以帮助你很多嵌套路由和有趣的事情,你不再需要使用确切的东西了

     <Routes>
        <Route path="/" element={<UsersIndex />} />
        <Route path=":id" element={<UserProfile />} />
        <Route path="me" element={<OwnUserProfile />} />
      </Routes>
Run Code Online (Sandbox Code Playgroud)

这就是新功能的样子