react-router – React Router – 是嵌套组件的反模式吗?
发布时间:2020-12-15 20:30:37 所属栏目:百科 来源:网络整理
导读:来自React Router的 docs: All children of a Switch should be Route or Redirect elements. Only the first child to match the current location will be rendered. 尽管如此,嵌套 Switch声明是允许的.我使用该模式来分解大量的路由: Switch Route path
来自React Router的
docs:
尽管如此,嵌套< Switch>声明是允许的.我使用该模式来分解大量的<路由>: <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>应避免陈述? 解决方法
嵌套< 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> 返回一系列路线会平掉< Switch>然而,声明的缺点是你必须添加关键道具以防止React发出警告. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |