我的组件是这样构建的:
function myComponent(props){
const [state, setState] = useState("WAIT")
function run(){
setState("LOAD");
props.apiFetch();
setState("WAIT");
}
return(<h1 onClick={run}>{status}</h1>)
}
当我单击该元素时,
state
一直显示为 WAIT,但从未显示为 LOAD。如果有任何反馈,我将不胜感激。
编辑: 将我的功能更改为
async function run(){
await setState("LOAD")
...
}
没有帮助
评论中所有建议的参考资料都有助于解释这里发生的事情。但这是对正在发生的事情的简单解释,可以帮助您解决问题(在被欺骗和删除之前):
function myComponent(props){
const [state, setState] = useState("WAIT")
function run(){
setState("LOAD");
// Yes, state is set to LOAD, albeit briefly.
props.apiFetch();
// fetch is an async api, and therefore non-blocking, i.e the next line of code runs immediately.
setState("WAIT");
// This runs immediately after the first setState, so you never actually see the state being set to LOAD. It just gets set right back to WAIT because Javascript doesn't wait for fetch to finish before moving on.
}
return(<h1 onClick={run}>{state}</h1>)
}
作为旁注,您需要将
await
应用于 props.apiFetch()
以获得您正在寻找的效果,而不是 setState
调用。虽然,根据获取返回的速度,您仍然可能看不到屏幕上的状态变化。