首页 > 解决方案 > 反应 onClick 多个处理函数问题

问题描述

对于按钮上的 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吗?

标签: javascriptreactjs

解决方案


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

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

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

this.setState({
    instrumentCount: tempCount
}, () => {
    this.HandleDecrmenet(1)
});

推荐阅读