简体   繁体   中英

Prevent React from re-rendering a specific child component

I have a react component that conditionally renders several child components. Simplified code is just:

render(): {
  const component1 = condition ? renderComponent2() : null;
  const component2 = renderComponent2();

  return (
    <div>
      {component1}
      {component2}
    </div>
  );
}

The problem is that component2 is getting destroyed and re-rendered whenever the condition changes. I'm trying to prevent that and keep the original element around. I tried adding a key to component2 with no luck.

[edit] This is happening even when component1 always exists and I change flag on it to hide it or not with CSS :/

Form the example code, your component2 will not be destroyed and re-mounted again. React will run any render and possibly other lifecycle methods, but React will Update the component in the DOM in place.

Maybe your code is more complicated. Which causes react to think that you are not re-rendering component2 , but instead, are trying to render a whole new component. But again, from your example code this is not clear.

You can find proof of concept codepen here , which does the following:

  • It renders 2 instances of component2 , with a green background.
  • Button can ( illegally ) change background color of the first component to red, outside of react's knowledge.
  • By clicking the button, react will re-render the 2 components.
  • The background-color remains red, which is proof that react only updates component, and does not destroy.

React will NOT reset the background color to green, because react thinks (from its virtual DOM) that the background color is unchanged and still green.

UPDATE: The codepen now also contains further proof of how it CAN happen:

  • if you change the type of HTML returned (from <p> element to <h1> element in proof of concept)
  • react will NOT recognize it as the same element, and destroy original and insert a new element.

PS: because your example code creates the component through a method call, any lifecycle methods (such as shouldComponentUpdate ) should NOT be applied. Rendering components through methods should only be done for simple components, ie react elements. See official docs here :

A ReactElement is a light, stateless , immutable, virtual representation of a DOM Element.

Have you tried doing it with shouldComponentUpdate ? This is exactly what this function should be used for. Just add it to your component2 and add proper condition inside.

如果condition状态发生变化,组件将自行重新渲染,这意味着component2也将被更改。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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