简体   繁体   English

即使组件树没有更改,我如何确保React创建组件的新实例?

[英]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.

相关问题 React:如何将状态更改应用于组件的所有实例,即使组件的任何一个实例的状态发生更改? - React : How to apply the state change to all instances of a Component, even if the state of any one instance of component is changed? React 组件在重新渲染时创建 state 的新实例,即使 state 没有更改 - React component create a new instance of the state when re-rendering even the state is not changed 如何确保React组件的状态正确? - How can I ensure that a React component's state is correct? 检测 React 中组件树的任何部分何时发生更改 - Detect when any part of component tree has changed in React 如何只允许存在 React 组件的单个实例? - How can I allow only a single instance of a React component to be present? 即使道具未更改,组件也会更新 - Component updates even though prop has not changed 如何在DOM体中渲染组件,即使某些其他组件呈现它的反应? - How can I render a component in DOM body even if some other component renders it in react? 如何在React中将子组件移到新的父组件? - How can I move my child component to new parent in React? React Native:重新渲染组件,但道具没有改变 - React Native: Component rerender but props has not changed 变量更改时反应刷新组件 - React refresh component when variable has changed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM