我有两个组件 FirstLayout
和 SecondLayout
需要 Header
用于显示完成页面的组件。
此刻我做出了这个决定,即呈现 Header
两个页面上的组件,当我从 /first
切换时不会重新呈现它至 /second
或来自 /second
至 /first
路径
function App() {
return (
<Route exact path={'/(first|second)'} component={Header} />
<Route exact path={'/first'} component={FirstLayout} />
<Route exact path={'/second'} component={SecondLayout} />
<Route exact path={'/third'} component={ThirdLayout} />
)
}
但是如果我使用下面的方法,其中FirstLayout
和 ThirdLayout
组件已包含 Header
组件,Header
每次我从 /first
切换时,组件都会重新渲染至 /second
或来自 /second
至 /first
路径
function App() {
return (
<Route exact path={'/fisrt'} component={FirstLayout} /> // FirstLayout already contains Header component
<Route exact path={'/second'} component={SecondLayout} /> // SecondLayout already contains Header component
<Route exact path={'/third'} component={ThirdLayout} />
)
}
因此,我的目标是在使用布局和路由时实现一些优雅的方法。有没有办法让 React 明白 Header 组件不应该以第二种方式重新渲染?
最佳答案
实际上,鼓励在 UI 的不同位置使用多个 Route 组件。所以您的第一个解决方案似乎是正确的。
// You can render a <Route> in as many places // as you want in your app. It will render along // with any other <Route>s that also match the URL. // So, a sidebar or breadcrumbs or anything else // that requires you to render multiple things // in multiple places at the same URL is nothing // more than multiple <Route>s.
关于javascript - 如何优雅地使用 react-router 中的布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668806/