简体   繁体   English

组件在卸载前正在渲染

[英]Component is rendering before unmounting

I have been working on a project, and I want a div ID before unmounting it.我一直在做一个项目,在卸载它之前我想要一个div ID。

I tried using the below code:我尝试使用以下代码:

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

but the div was set to null before it came to useEffect.但是div在使用Effect之前被设置为null

To figure it out, I wrote an example code, and from that, I observed something really odd React is rendering component before it unmounts.为了解决这个问题,我写了一个示例代码,从中我观察到一些非常奇怪的 React 在卸载之前渲染组件。

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.从 useEffect 返回 function 允许你自己清理,比如删除事件监听器和取消订阅。 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.如果您想知道要通过单击按钮删除哪个元素,可以在将单击处理程序提供给按钮时部分应用 function。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM