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

时间:2018-04-02 15:49:01

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

来自React Router的docs

  

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

....

如果有更好的方法来分解大量路由并且应该避免使用嵌套的<Switch>语句,那我很好奇吗?

2 个答案:

答案 0 :(得分:2)

嵌套[[hey_1|10]] [[hey_1|10], [hey_2|10]] 语句使组件树看起来像这样。不必要使树变得更复杂,并且可能使调试变得更加困难。

Screenshot of React Dev Tools with nested Switch Statements

您可以通过如下方式修改现有代码来修改嵌套:

Traceback (most recent call last):
  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pip\basecommand.py", line 209, in main
    status = self.run(options, args)

  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pip\commands\install.py", line 299, in run
    requirement_set.prepare_files(finder)

  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pip\req\req_set.py", line 356, in prepare_files
    discovered_reqs.extend(self._prepare_file(
  File "C:\Program Files (x86)\IronPython 2.7\Lib\contextlib.py", line 35, in __exit__
    self.gen.throw(type, value, traceback)

  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pip\utils\logging.py", line 36, in indent_log
    yield

SystemError: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.

返回一组路由会使<Switch>语句变平,但是这样做的缺点是,您必须添加const FooRouter = () => ( [ <Route exact path="/foo/new" component={NewFoo} key={1} />, <Route exact path="/foo/:id" component={ViewFoo} key={2} /> ] ); const BarRouter = () => ( <Route exact path="/bar/new" component={NewBar} /> ); ... <Switch> {FooRouter()} {BarRouter()} <Route path="/baz" component={BazRouter} /> </Switch> 道具以防止React发出警告。

答案 1 :(得分: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>

这就是新功能的外观