this.setState((prevState) => { console.log("entry") let selected = this.state.selected selected.push(id) return { selected } })
会触发控制台打印两次entry
因为js对象都是浅拷贝,所以应该是直接修改state导致的结果。具体原理暂时不清楚。
解决:
使用深拷贝。当数据比较复杂的时候,下面的方法有bug。具体请搜索“js深拷贝”相关文章
this.setState((prevState) => { let selected = [] prevState.selected.map((item) => { selected.push(item) }) selected.push(id) return { selected } })