假设以下示例:
const example = () => {
const [objects, setObjects] = useState([])
const asyncFunction = async() => {
// This will trigger the API and assume it takes around 10 seconds to run
let result = api.fetchObjects().then((result) => {
// Here, setObjects will be called with the value it had at the moment the function started executing, not the actual value
setObjects(result)
}
}
}
我的问题是,执行 setObjects(result) 和使用更新状态的最佳方法是什么?假设用户可以在这 10 秒内通过应用程序中的不同方式将对象添加到该状态。
我找到了使用 useEffect 的解决方案,如下所示:
// Instead of setObjects(result)
const [updateObjects, setUpdateObjects] = useState(null)
setUpdateObjects(result)
useEffect(() => {
if (updateObjects !== null) {
setObjects(updateObjects)
setUpdateObjects(null)
}