简体   繁体   English

React Hooks:当只有 props.children 值发生变化时,如何防止重新渲染整个组件?

[英]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:所以我的问题是:

  1. Can I prevent Layout re-rendering when the props.children value changes?当 props.children 值发生变化时,我可以防止布局重新渲染吗?
  2. If not, is the only way to prevent Layout from rerendering on each route change to move the Switch component out of the Layout's children?如果不是,那么防止 Layout 在每次路由更改时重新渲染以将 Switch 组件移出 Layout 的子项的唯一方法是什么?

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创建MenuBarFooter组件来防止它们重新渲染:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM