我偶然發(fā)現(xiàn)了一個對我來說非常奇怪的問題,但很可能很容易解釋。演示讓我們假設(shè)以下 React 組件import React, { useState, useEffect, useCallback } from "react";export default function App() { const [test, setTest] = useState(); const doSomething = () => { // TODO: Why does this returns the inital state value? Hoisting? console.log(test); }; const doSomethingWithCallback = useCallback(doSomething, [test]); useEffect(() => { setTest("asas"); window.setTimeout(() => doSomething(), 2000); document.addEventListener("click", doSomethingWithCallback); return () => { document.removeEventListener("click", doSomethingWithCallback); }; }, [doSomethingWithCallback]); return ( <div className="App"> <h1>Click anywhere</h1> </div> );}(參見CodeSandbox)問題看一下TODO代碼中的注釋。為什么控制臺會記錄最初設(shè)置的doSomething狀態(tài),即回調(diào)變體在調(diào)用時返回“真實”當(dāng)前狀態(tài)?testundefined這是 React 正在做的某種提升或性能優(yōu)化嗎?
React - React 應(yīng)用程序中閉包的影響
天涯盡頭無女友
2023-10-20 10:27:48