javascript - 反应 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
没有使用更新状态时。
我应该使用类似async
or的东西await
吗?
解决方案
setState(updater[, callback])
是一个异步函数:
https://facebook.github.io/react/docs/react-component.html#setstate
您可以在 setState 使用第二个参数回调完成后执行一个函数,例如:
this.setState({
instrumentCount: tempCount
}, () => {
this.HandleDecrmenet(1)
});
推荐阅读
- hash - 如何生成 Shopify 废弃购物车“关键”参数?(电子邮件哈希?)
- ios - 您如何将节点位置调整为横向和纵向
- c - C 和 ASCII 代码:如果 128 的范围是从 -128 到 127,它怎么能代表一个字符?
- google-app-engine - 在 GCP 中,是否有从 API 抓取数据的规范方法?
- android - 如何检测软件键盘在 Android 电视(消防电视)上是否可见?
- ios - 如何默认扩展 iOS Today Widget?
- java - Android Studio 3.2.1 上的“无法访问 org.json.JSONStringer.Scope”
- c++ - 作为参数传递给函数模板时如何隐式转换类模板对象?
- dynamics-crm - 将社交窗格中的活动配置为默认“进行中”
- c# - 如果布尔值标记为 false,Selenium C# 显示自定义异常?