Javascript 单击多个处理程序函数时作出反应
对于按钮上的onClick事件,我有两个处理程序函数。基本上,它们做相同的事情,但一个是递增状态数组中的元素(作为参数传递),而另一个是递减(但不是相同的变量)。假设我有一个由两个元素组成的数组。我希望第一个元素递增,第二个元素递减(Javascript 单击多个处理程序函数时作出反应,javascript,reactjs,Javascript,Reactjs,对于按钮上的onClick事件,我有两个处理程序函数。基本上,它们做相同的事情,但一个是递增状态数组中的元素(作为参数传递),而另一个是递减(但不是相同的变量)。假设我有一个由两个元素组成的数组。我希望第一个元素递增,第二个元素递减(array[0]++array[1]--) 我还有一个执行这两个方法的按钮 onClick = {() => { this.HandleIncrement(0); this.HandleDecrmenet(1); } } 输出不
array[0]++array[1]--
)
我还有一个执行这两个方法的按钮
onClick = {() => {
this.HandleIncrement(0);
this.HandleDecrmenet(1);
}
}
输出不理想。如果这是数组=[0 1]
,我希望输出是[1 0]
,但是
输出为[0]
。我认为这是因为这两个函数同时执行,所以当它们setState
时,HandleDecrement
没有使用更新的状态
我应该使用类似于async
或wait
的东西吗 setState(更新程序[,回调])
是一个异步函数:
您可以在setState完成后使用第二个参数回调执行函数,如:
this.setState({
instrumentCount: tempCount
}, () => {
this.HandleDecrmenet(1)
});
我会这样做
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) )
}}
或者使用wait
onClick={async ()=> {
await this.handleIncrement(1)
this.handleDecrement(0)
}}
您不能等待状态更改,因为它们是在内部处理的。建议您编写一个附加函数来处理这两个更改(但只调用一次
setState
)。Clarity的建议,如果编码正确的话,将会起作用:这已经起作用了,谢谢!对不起,我发现了一个骗局。
onClick={async ()=> {
await this.handleIncrement(1)
this.handleDecrement(0)
}}