简体   繁体   English

如何使用反应 useState 钩子防止竞争条件

[英]How to prevent race conditions with react useState hook

I have a component that uses hooks state (useState) api to track the data.我有一个组件,它使用钩子状态 (useState) api 来跟踪数据。

The object looks like this对象看起来像这样

const [data,setData] =  React.useState({})

Now I have multiple buttons which make API requests and set the data with the new key现在我有多个按钮可以发出 API 请求并使用新密钥设置数据

setAPIData = (key,APIdata) => {

    const dup = {
      ...data,
      [key]:APIdata
    }
    setData(dup)
}

Now if I make multiple requests at the same time , it results in race conditions since setting state in react is asynchronous and I get the previous value.现在,如果我同时发出多个请求,则会导致竞争条件,因为在 react 中设置状态是异步的,并且我获得了先前的值。

In class-based components, we can pass an updater function to get the updated value, how to do this hooks based component.在基于类的组件中,我们可以通过一个 updater 函数来获取更新的值,这个基于钩子的组件是如何做的。

You must use setData with a function as its argument.您必须使用带有函数的 setData 作为其参数。 Then it will always get the previous state, no matter what order it will be called.那么它总是会得到之前的状态,不管它会以什么顺序被调用。

  setAPIData = (key, APIdata) => {
    setData(prevData => ({
      ...prevData,
      [key]: APIdata
    }));
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM