英文:
React seems to not execute sequentially
问题
以下是您提供的代码的中文翻译部分:
我的组件是这样构建的:
function myComponent(props){
const [state, setState] = useState("等待")
function run(){
setState("加载中");
props.apiFetch();
setState("等待");
}
return(<h1 onClick={run}>{state}</h1>)
}
当我点击这个元素时,state
始终显示为 "等待",而不显示为 "加载中"。我会感激任何反馈。
编辑:
将我的函数更改为
async function run(){
await setState("加载中")
// ...
}
不起作用。
英文:
My component is built like this:
function myComponent(props){
const [state, setState] = useState("WAIT")
function run(){
setState("LOAD");
props.apiFetch();
setState("WAIT");
}
return(<h1 onClick={run}>{status}</h1>)
}
When I click on the element, state
is displayed as WAIT the whole time, but never as LOAD. I'd appreciate any feedback.
EDIT:
Changing my function to
async function run(){
await setState("LOAD")
...
}
does not help
答案1
得分: 5
所有在评论中建议的参考资料都有助于解释这里发生的事情。但是这里有一个简单的解释,帮助你理解(在此之前被重复和删除之前):
function myComponent(props){
const [state, setState] = useState("WAIT")
function run(){
setState("LOAD");
// 是的,状态被设置为LOAD,尽管是短暂的。
props.apiFetch();
// fetch是一个异步api,因此是非阻塞的,即下一行代码立即运行。
setState("WAIT");
// 这在第一个setState之后立即运行,所以你实际上从未看到状态被设置为LOAD。它立即被设置回WAIT,因为JavaScript在继续之前不会等待fetch完成。
}
return(<h1 onClick={run}>{state}</h1>)
}
顺便说一句,你需要将await
应用于props.apiFetch()
,而不是setState
调用,以获得你想要的效果。尽管根据fetch返回的速度,你仍然可能看不到屏幕上状态的变化。
英文:
All of the suggested references in the comments help explain what's happening here. But here's a simple explanation of what's happening to help you out (before this gets duped and removed):
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>)
}
As a side note, you would need to apply the await
to the props.apiFetch()
to get the effect you're looking for, not the setState
call. Although, depending on the speed of the fetch return, you still may not see the state changing on screen.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论