React 似乎不按顺序执行

huangapple go评论68阅读模式
英文:

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(&quot;WAIT&quot;)
  function run(){
    setState(&quot;LOAD&quot;);
    props.apiFetch();
    setState(&quot;WAIT&quot;);
  }
  return(&lt;h1 onClick={run}&gt;{status}&lt;/h1&gt;)
}

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(&quot;LOAD&quot;)
 ...
}

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(&quot;WAIT&quot;)
  function run(){
    setState(&quot;LOAD&quot;);
    // 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(&quot;WAIT&quot;);
    // 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&#39;t wait for fetch to finish before moving on.

  }
  return(&lt;h1 onClick={run}&gt;{state}&lt;/h1&gt;)
}

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.

huangapple
  • 本文由 发表于 2023年3月3日 23:37:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定