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:
component2
, with a green background. 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:
<p>
element to <h1>
element in proof of concept) 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.