我有一个布局组件,如下所示:
export const Layout = (props) => {
return (
<div>
<MenuBar />
{props.children}
<Footer />
</div>
);
};
...并且我想使用此Layout组件来呈现不同页面的内容,如下所示:
export const App = () => {
return (
<div>
<Router>
<Layout>
<Switch>
<Route exact path="/">
<PageHome />
</Route>
<Route path="/about">
<PageAbout />
</Route>
</Switch>
<Layout />
</Router>
</div>
);
};
我现在遇到的问题是,每次路线更改时,props.children值都会更改,因此整个Layout组件(包括MenuBar和Footer)以及页面内容都将重新呈现。所以我的问题是:
答案 0 :(得分:2)
Layout
本身必须重新渲染,因为它有新的子代,但是您可以使用React.memo创建MenuBar
和Footer
组件,以防止重新渲染它们:
const MenuBar = React.memo(function MyComponent(props) {
/* render using props, it won't re rerender unless props change */
});