reactjs / reactjs/react.dev

useEffect Clean-Up Function Executes After Component is Removed

未關閉
#3,427 6 則留言 3 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

主要語言
JavaScript
星號
11.8k
分支
7.9k
平均合併
1 天 11 小時
30 天內合併 PR
11

描述

This behavior has changes in React version 17.0.x.

Clean-up function should execute when the component unmounts, and I've noticed in React v.17 by the time cleanup function executes, React referenced elements are no longer available.

Working example with React v.16
Example with React v.17

Notice unmountSuccessful logs before divRef in React v.17 example.

This is the only relevant change I noticed from the changelog.

If the behavior of useEffect clean-up has changed it should be reflected on the docs.

Code Snippet:

const App = () => {
  const divRef = React.useRef(null);
  
  React.useEffect(() => {
    console.log('divRef ::', divRef.current)
    return function cleanUp() {
      console.log('[cleanUp] divRef ::', divRef.current)
    }
  }, [])
  return (
    <div ref={divRef}>
      Open Browser's Console For Output
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

const unmountApp = () => {
  console.log('unmounting root...')
  const node = document.getElementById('root');
  const unmountSuccessful = ReactDOM.unmountComponentAtNode(node);
  console.log('unmountSuccessful ::', unmountSuccessful)
};

window.setTimeout(unmountApp, 1500);

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從 issue 中連結的 React useEffect 文件開始,將其中關於清理的措辭與兩個 CodePen 範例中展示的 React 17 行為進行比較。閱讀與相關變更對應的已連結 changelog pull request。完成的標準是文件準確說明清理何時執行,以及被參照的元素是否仍然可用。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
javascript, react
領域
documentation
Issue 類型
文件
難度
3/5
預估耗時
1-2 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。