Sve*_*ven 0 javascript asynchronous reactjs
我的组件是这样构建的:
function myComponent(props){
const [state, setState] = useState("WAIT")
function run(){
setState("LOAD");
props.apiFetch();
setState("WAIT");
}
return(<h1 onClick={run}>{status}</h1>)
}
Run Code Online (Sandbox Code Playgroud)
当我单击该元素时,state始终显示为“等待”,但从不显示为“加载”。如果有任何反馈,我将不胜感激。
编辑:将我的功能更改为
async function run(){
await setState("LOAD")
...
}
Run Code Online (Sandbox Code Playgroud)
没有帮助
评论中所有建议的参考文献都有助于解释这里发生的事情。但这里有一个简单的解释来帮助您解决问题(在这被欺骗和删除之前):
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>)
}
Run Code Online (Sandbox Code Playgroud)
作为旁注,您需要将 应用于await来props.apiFetch()获得您正在寻找的效果,而不是setState调用。尽管如此,根据获取返回的速度,您仍然可能看不到屏幕上的状态变化。
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |