【问题标题】:React Router - are nested <Switch> components an anti-pattern?React Router - 嵌套的 <Switch> 组件是反模式吗?
【发布时间】:2018-09-11 20:27:24
【问题描述】:

来自 React Router 的 docs

&lt;Switch&gt; 的所有子元素都应该是 &lt;Route&gt;&lt;Redirect&gt; 元素。只有第一个匹配当前位置的子节点才会被渲染。

尽管如此,嵌套的&lt;Switch&gt; 语句是允许的。我使用该模式分解大量&lt;Routes&gt;

<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>
)

....

想知道是否有更好的方法来分解大量路由以及是否应该避免嵌套的&lt;Switch&gt; 语句?

【问题讨论】:

  • 您开始提问时的引述解决了我的问题。在对 React 有用的建议和警告感到高兴之后,在使用其他库时仅仅因为您不记得文档而出现问题是很痛苦的。

标签: react-router react-router-v4 react-router-dom


【解决方案1】:

当您有很多嵌套路线时,您可以很好地解决它,您可以将它们穿过应用程序并制作动态路线 但很快 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 /> },
      ]
    }
  ]);

introduction to react-router-dom v6 他们有一些很酷的新功能值得关注 其中之一是用女巫代替,通过嵌套路线和有趣的事情帮助你很多不再需要使用确切的

     <Routes>
        <Route path="/" element={<UsersIndex />} />
        <Route path=":id" element={<UserProfile />} />
        <Route path="me" element={<OwnUserProfile />} />
      </Routes>

这就是新功能的外观

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 2017-10-05
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多