在反应路由器的官方文档中打开sidebar example。您可以看到not
在没有ul
的情况下呈现,因为它应该在屏幕上,而不管网址如何。打开React DevTools,选中Route
复选框,然后单击侧栏中的任何菜单项。您会注意到Highlight updates
下的元素会在每次点击时重新呈现。在我看来,这不是理智的行为,ul
下的反应元素不应该通过路由更改重新呈现,因为它们不是由反应路由器ul
组件呈现的。有没有办法阻止他们重新渲染?
答案 0 :(得分:1)
路由器组件依赖于更改的上下文,并且当更新上下文值时,它会触发子项的重新呈现以进行匹配并呈现适当的路由。现在,因为ul element
直接写为child of Router
,所以它也会被重新渲染。虽然react执行虚拟dom比较并且DOM不会被重新渲染,但您可以使用PureComponent
并在Component
const SidebarExample = () => (
<Router>
<div style={{ display: "flex" }}>
<div
style={{
padding: "10px",
width: "40%",
background: "#f0f0f0"
}}
>
<Route component={Elements}/>
{routes.map((route, index) => (
// 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.
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.sidebar}
/>
))}
</div>
<div style={{ flex: 1, padding: "10px" }}>
{routes.map((route, index) => (
// Render more <Route>s with the same paths as
// above, but different components this time.
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.main}
/>
))}
</div>
</div>
</Router>
)
class Elements extends React.PureComponent {
render() {
return (
<ul style={{ listStyleType: "none", padding: 0 }}>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/bubblegum">Bubblegum</Link>
</li>
<li>
<Link to="/shoelaces">Shoelaces</Link>
</li>
</ul>
)
}
}