报错: Warning: Cannot update during an existing state transition (such as within render)
<Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst}
onClick={this.onRemove (index)}>
<Icon type={'delete'}/>删除
</Button>
)
onRemove = (index) => {
const { placeTime } = this.state
console.log(placeTime, index);
placeTime.splice(index, 1)
this.setState({
placeTime
})
}
删除按钮绑定的onRemove
点击事件,想要带着参数index去执行,但这种操作是不允许的,刚好在事件函数中也有setState操作,这样就会陷入到死循环
中,不停的改变state,render()又不停的被执行。
解决方案
// 一
<Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst}
onClick={()=>this.onRemove (index)}>
<Icon type={'delete'}/>删除
</Button>
// 二
<Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst}
onClick={this.onRemove .bind(this,index)}>
<Icon type={'delete'}/>删除
</Button>
网友评论