简体   繁体   中英

Can a React component be used in the unmounted state?

I have a React component that creates an event listener, and displays a list of links. Once the user clicks on a link the componentWillUnmount method is called and a new page displayed. My component continues to function and handle events after it has been unmounted. This works as intended as I am keeping track of whether my control is mounted or not and calling functions passed in through props based on the mounted/unmounted state.

Everything seems to be working fine, but I've read in the React docs, "componentWillUnmount() is invoked immediately before a component is unmounted and destroyed ". I am also aware that isMounted is an anti-pattern so I am keeping track of whether the control is mounted myself. Is it just a matter of time before my component is destroyed or is my event listener keeping it from being destroyed?

I think the solution for your problem is using a library like Redux . It will handle your state and actions for you, so you don't have to worry about components in an unmounted state.

That being said, this is actually a known memory leak issue in React. You can see the issue here .

componentWillUnmount() Is designed for handling the cleanup of a component. This includes cleaning up event listeners and timers etc. I believe the correct approach would be to remove the event listener in this function.

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