简体   繁体   中英

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. 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. 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 .

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.

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. 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

Could you tell us what the third-party library that you are using is? Perhaps there is a better workaround for your problem!

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