为什么异步调用后状态不会改变

问题描述 投票:0回答:1

我有这种情况,在函数内部我更改状态,调用异步方法,然后要使用更新后的状态。问题是异步调用后运行的状态没有改变:

function MyComponent(){
 const [values, setValues] = useState<number[]>([]);
 const updateValue = () => {
  setValues(values.push(1));
  myAsyncMethod().then(()=>{
   console.log(values); //still empty array '[ ]' !
   setValues(values.remove(1)); //no value to remove
  });
 };
 return(
  <OtherComponent values={values} updateValue={updateValue}/>
 );
}

缺少什么?我不想使用'useRef',因为我想在值更改时重新呈现。

javascript reactjs react-hooks
1个回答
1
投票

从您的代码块:

const updateValue = () => {
  setValue(2);
  myAsyncMethod().then(()=>{
   console.log(value); //still '1' !
  });
};

setValue也是异步的。因此,这就是为什么您仍将值设为1的原因。根据您的方案,您将获得要设置的值。您可以通过以下方式而不是通过状态变量进行传递:

const updateValue = newValue => {
  setValue(newValue);
  myAsyncMethod().then(()=>{
   console.log(newValue);
  });
};

希望这会对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.