[英]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. React根据该树中的元素名称来更新其组件树。
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). ...使用相同的<MyComponent>
实例生成React(因为组件名称没有改变)。 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. 因此,如果不更改prop 'x'
,我希望实例化一个新实例,而不是使用相同的MyComponent
实例。
Untested, but I think you could trick React and add the prop as a key
on the component. 未经测试,但是我认为您可以欺骗React并将prop作为组件上的key
添加。
<div>
<MyComponent enabled key={enabled.toString()} />
</div>
Since you're familiar with the reconciliation docs, I imagine you know what keys do already ;) 由于您熟悉对帐单据,因此我想您已经知道哪些键已经执行了;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.