【问题标题】:Why do react elements outside of Route re-render?为什么 Route 之外的 react 元素会重新渲染?
【发布时间】:2018-06-12 10:16:09
【问题描述】:
在 react 路由器的官方文档中打开sidebar example。你可以看到ul 是在没有Route 的情况下呈现的,因为它应该出现在屏幕上,而与url 无关。打开 React DevTools,选中 Highlight updates 复选框并单击侧栏中的任何菜单项。您会注意到ul 下的元素在每次点击时都会重新渲染。在我看来,这是不理智的行为,ul 下的反应元素不应该随着路由更改而重新渲染,因为它们不是由反应路由器 Route 组件渲染的。有没有办法阻止它们重新渲染?
【问题讨论】:
标签:
reactjs
react-router
react-router-v4
react-router-dom
【解决方案1】:
Router 组件依赖于上下文进行更改,并且每当更新上下文值时,它都会触发子组件的重新渲染以进行匹配并渲染适当的路由。现在由于ul element 直接写为child of Router,它也被重新渲染。尽管 react 会执行 virtual-dom 比较并且不会重新渲染 DOM,但您可以通过使用 PureComponent 并在 Component 中写入 ul 元素来避免它
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>
)
}
}