react 数组删除某一项更新setState无效的问题,react js怎么删除数组某一项,splice删除了某一项页面数据却不变

文章讲述了在React中,使用`splice`删除数组项后通过`setState`更新状态的问题。作者提供了错误实例和最优雅的做法,强调了深拷贝的必要性。正确做法是先复制数组再进行修改,确保state的正确更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:相信许多人应该踩过这个坑,使用数组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)

如果帮你解决到了问题请点个赞(●'◡'●)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值