我有一个简单的 React 组件(Hooks):
// inside React component
import { someExternalFunction } from "functions"
const [value, setValue] = useState(0)
const handleChange = () => {
someExternalFunction(value, setValue)
}
// outside of React component
const someExternalFunction = (value, setValue) => {
console.log(value) // 0
// testing "set" method
setValue(100) // working
// "set" is async, so lets wait
// testing "get" method
setTimeout(() => console.log(value), 5000) // 0
// not working
}
问题:“值”/状态总是相同的,它在状态传递给函数的那一刻被捕获。
问题:如何访问外部函数的最新状态?
澄清:当然,它不适用于“值”/状态,我只是试图说明我面临的问题,即使用为函数提供最新状态的首选方法(通过直接引用)。