前言:相信许多人应该踩过这个坑,使用数组splice方法删除时候,然后通过setState更新数组,setState不工作。打印原数组已经删除了某一项,页面数据却不变。
1、错误实例1
removeEntities = (entities) => {
const { arr } = this.state;
arr.map((item, index) => {
if (item === entities) {
arr.splice(index, 1);
this.setState({
arr: arr,
});
console.log(arr) //这里打印发现arr已经发生了变化,但是setState在页面上数据却不改变是不是很奇怪呢?
}
});
};
2、错误实例2
let dl = documentList // 顶部数据
let ol = otherList // 底下数据
// 底下删一个
ol.splice(index, 1)
// 顶部插入一个
dl.unshift(item)
if(dl.length > 2){
// 长度大于3,底部插入一个 顶部删除最后一个
let lastIndex = dl.length - 1;
ol.unshift(dl[lastIndex])
dl.pop()
}
setOtherList(ol)
setDocumentList(dl)
3、最优雅最直观做法
removeEntities = (entities) => {
const { ownerEntitiesList } = this.state;
const newData = [...ownerEntitiesList]; //这里是重点,直接拷贝一份出来,
newData.map((item, index) => {
if (item === entities) {
newData.splice(index, 1);
this.setState({
ownerEntitiesList: newData, //直接setState这个改变后的数组
});
}
});
};
const dl = [...documentList]; //这里是重点,直接拷贝一份出来,
const ol = [...otherList]; //这里是重点,直接拷贝一份出来,
// 底下删一个
ol.splice(index, 1)
// 顶部插入一个
dl.unshift(item)
if(dl.length > 2){
// 长度大于3,底部插入一个 顶部删除最后一个
let lastIndex = dl.length - 1;
ol.unshift(dl[lastIndex])
dl.pop()
}
setOtherList(ol)
setDocumentList(dl)
如果帮你解决到了问题请点个赞(●'◡'●)