简体   繁体   中英

Component is rendering before unmounting

I have been working on a project, and I want a div ID before unmounting it.

I tried using the below code:

useEffect(()=>
  return()=>getId
),[state])

but the div was set to null before it came to useEffect.

To figure it out, I wrote an example code, and from that, I observed something really odd React is rendering component before it unmounts.

Example code

you can see similar behavior on clicking test button in above mention code.

If someone has any idea how it works, Please explain or suggest any alternate method.

Returning a function from a useEffect allows you to clean up after yourself, like removing event listeners and unsubscribing from something. It shouldn't really be thought of as an "unmount" callback.

If you want to know what element you're going to be removing with a button click, you could partially apply a function when you give the click handler to the button. This allows you to have a single click handler for all your buttons, where you give it a bit of extra context depending on where you implement it.

const handleClick = (id: string) => (event: ChangeEvent<HTMLButtonElement>) => {
  // ...handle the click
}

// ...in your render fn
<button onClick={handleClick("div-id-1")}>Remove Div 1</button>

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