[英]React Hooks: how to prevent re-rendering the whole component when only the props.children value changes?
I have a Layout component that looks like this:我有一个看起来像这样的布局组件:
export const Layout = (props) => {
return (
<div>
<MenuBar />
{props.children}
<Footer />
</div>
);
};
...and I want to use this Layout component to render content for different pages like so: ...我想使用这个 Layout 组件来呈现不同页面的内容,如下所示:
export const App = () => {
return (
<div>
<Router>
<Layout>
<Switch>
<Route exact path="/">
<PageHome />
</Route>
<Route path="/about">
<PageAbout />
</Route>
</Switch>
<Layout />
</Router>
</div>
);
};
Now the problem I have is that each time the route changes, the props.children value changes and so the whole Layout component (including the MenuBar and Footer) get re-rendered as well as the page content.现在我遇到的问题是,每次路由更改时,props.children 值都会更改,因此整个 Layout 组件(包括 MenuBar 和 Footer)以及页面内容都会重新呈现。 So my questions are:
所以我的问题是:
The Layout
itself must be re rendered, because it has new children, however you can prevent MenuBar
and Footer
components from re rendering by creating them using React.memo :必须重新渲染
Layout
本身,因为它有新的子级,但是您可以通过使用React.memo创建MenuBar
和Footer
组件来防止它们重新渲染:
const MenuBar = React.memo(function MyComponent(props) {
/* render using props, it won't re rerender unless props change */
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.