简体   繁体   中英

How can I ensure that React creates a new instance of a component, even if the component tree has not changed?

React updates its component tree based on the names of the elements in that tree.

For example:

<div>
  <MyComponent/>
</div>

And:

<div>
  <MyComponent enabled/>
</div>

...results in React using the same <MyComponent> instance (because the component name did not change). This is very useful because it ensures that internal state within the component instance persists.

See the documentation for more details.

My question: "Is there a way to force a new instance to be created in certain circumstances?"

So rather than using the same MyComponent instance, I would like a new one to be instantiated if (let's say) prop 'x' has changed.

Untested, but I think you could trick React and add the prop as a key on the component.

<div>
  <MyComponent enabled key={enabled.toString()} />
</div>

Since you're familiar with the reconciliation docs, I imagine you know what keys do already ;)

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