【问题标题】:How can I ensure that React creates a new instance of a component, even if the component tree has not changed?即使组件树没有更改,如何确保 React 创建组件的新实例?
【发布时间】:2019-03-16 20:04:58
【问题描述】:

React 根据树中元素的名称更新其组件树。

例如:

<div>
  <MyComponent/>
</div>

还有:

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

...导致 React 使用相同的 &lt;MyComponent&gt; 实例(因为组件 name 没有改变)。这非常有用,因为它可以确保组件实例中的内部状态保持不变。

更多详情请见the documentation

我的问题:“有没有办法在某些情况下强制创建一个新实例?”

因此,与其使用相同的 MyComponent 实例,我希望在(假设)prop 'x' 发生变化时实例化一个新实例。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

未经测试,但我认为你可以欺骗 React 并将 prop 添加为组件上的 key

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

由于您熟悉对帐文档,我想您已经知道键的作用;)

【讨论】:

  • 哇。错过了明显的解决方案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
相关资源
最近更新 更多