0

对于按钮上的 onClick 事件,我有两个处理函数。基本上他们做同样的事情,但一个是增加状态数组中的一个元素(作为参数传递),而另一个是减少(但不是同一个变量)。假设我有一个包含两个元素的数组。我希望第一个元素递增,第二个元素递减(array[0]++ array[1]--)。

HandleIncrement = instrumentUp => {
  // create a shallow copy of the array
  const tempCount = [...this.state.instrumentCount];
  // increment the desired instrument
  tempCount[instrumentUp] += 1;
  // update the state
  this.setState({
    instrumentCount: tempCount
  });
};

HandleDecrement = instrumentDown => {
  // create a shallow copy of the array
  const tempCount = [...this.state.instrumentCount];
  // decrement the desired instrument
  tempCount[instrumentDown] -= 1;
  // update the state
  this.setState({
    instrumentCount: tempCount
  });
};

我还有一个执行这两种方法的按钮。

 onClick = {() => {
     this.HandleIncrement(0);
     this.HandleDecrmenet(1);
   }
 }

输出是不希望的。如果这是array = [0 1],我希望输出是 ,[1 0]但是输出是[0 0]setState我认为这是因为这两个函数同时执行,所以当它们HandleDecrement没有使用更新状态时。

我应该使用类似asyncor的东西await吗?

4

2 回答 2

0

setState(updater[, callback])是一个异步函数:

https://facebook.github.io/react/docs/react-component.html#setstate

您可以在 setState 使用第二个参数回调完成后执行一个函数,例如:

this.setState({
    instrumentCount: tempCount
}, () => {
    this.HandleDecrmenet(1)
});
于 2020-03-09T09:45:16.780 回答
0

我会做这样的事情

handleIncrement = (index) => new Promise(resolve => {
   const tempCount =  Object.assign([], this.state.instrumentCOunt);
  // increment the desired instrument
  tempCount[index] += 1;
  // update the state
  this.setState({
    instrumentCount: tempCount
  }, () => resolve(this.state.instrumentCount) ) ;
})

handleDecrement = (index) => new Promise(resolve => {
   const tempCount =  Object.assign([], this.state.instrumentCOunt);
  tempCount[index] -= 1;
  this.setState({
    instrumentCount: tempCount
  }, () => resolve(this.state.instrumentCount) ) ;
})


onClick={ ()=> {
   this.handleIncrement(1)
    .then(()=>  this.handleDecrement(0) )
}}

或使用等待

onClick={async ()=> {
  await  this.handleIncrement(1)
  this.handleDecrement(0) 
}}
于 2020-03-09T10:34:50.967 回答