[英]Using the key prop to force re-mount of a React component
We have a case where we need to re-mount a third party component to trigger stuff that happens in the mounting process.我们有一个案例,我们需要重新安装第三方组件来触发安装过程中发生的事情。 Not to confuse with update/rerender that we'd prefer, but we have restricted control over the component.
不要与我们更喜欢的更新/重新渲染混淆,但我们限制了对组件的控制。
However, we've been searching around and found that quite many suggest using the key prop and change the value once the component should re-mount.然而,我们一直在四处寻找,发现很多人建议使用 key prop 并在组件重新安装后更改值。 We've tested it out and it seems to work as expected but the thing is that there is no official documentation of this approach at https://reactjs.org , and I have never seen it before.
我们已经对其进行了测试,它似乎按预期工作,但问题是https://reactjs.org 上没有关于这种方法的官方文档,而且我以前从未见过它。 Only together with lists/iterations but not on single elements.
仅与列表/迭代一起使用,但不能与单个元素一起使用。
What do you think?你怎么认为?
You can find an indirect answer to your question in React docs .您可以在React docs 中找到问题的间接答案。
Keys should be stable, predictable, and unique.
密钥应该是稳定的、可预测的和唯一的。 Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
不稳定的键(如 Math.random() 产生的键)将导致不必要地重新创建许多组件实例和 DOM 节点,这可能导致子组件的性能下降和状态丢失。
So the re-mount behavior is intended.所以重新安装行为是有意的。 IMHO as part of the reconciliation algorithm, it is also stable.
恕我直言,作为和解算法的一部分,它也是稳定的。
Using keys only makes sense in lists (arrays) inside JSX.仅在 JSX 中的列表(数组)中使用键才有意义。 Otherwise this shouldn't have any effect and if it does I wouldn't want to rely on this behaviour in production as I don't think it's intended
否则这不应该有任何影响,如果确实如此,我不想在生产中依赖这种行为,因为我认为这不是故意的
https://reactjs.org/docs/lists-and-keys.html#keys https://reactjs.org/docs/lists-and-keys.html#keys
Could you tell us what the third-party library that you are using is?你能告诉我们你使用的第三方库是什么吗? Perhaps there is a better workaround for your problem!
也许您的问题有更好的解决方法!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.