#独家
求助!react 改变(浅拷贝)数组对象的某一个值,列表没有自动更新?

2023-04-18 0 2,703

可能因为改变了系统node的版本,我重新npm了一个老项目的node_modules

    addPortIconBtn(index)  {
        this.state.machineListData[(this.state.current - 1) * 10 + index].iscreateport = true
        this.setState({
            machineListData: this.state.machineListData
        })
    }

这时我发现项目中类似这种改变数组某个值的写法,视图都不再更新,我确定数据是变化的,于是我尝试浅拷贝的写法

addPortIconBtn(index)  {
        let arr = [...this.state.machineListData]
        arr[(this.state.current - 1) * 10 + index].iscreateport = true
        this.setState({
            machineListData: arr
        })
    }

这样依然不生效,于是我创建了最新版本的react脚手架,发现第一种写法也是可行,所以不知道到底哪里出了问题,视图是antd(4.15.2)的table,

<Table columns={this.state.columns} dataSource={this.state.machineListData} rowKey={(record) => record.dockerid}/>

react版本是16.13.1

你可以创建一个新数组,并把数组中的对象也进行浅拷贝,就行了

addPortIconBtn(index) {
  // 创建一个新数组,并将数组中的对象进行浅拷贝
  let arr = this.state.machineListData.map((item) => ({ ...item }));

  // 更新指定索引处的对象属性
  arr[(this.state.current - 1) * 10 + index].iscreateport = true;

  // 使用新数组更新 state
  this.setState({
    machineListData: arr
  });
}

不要直接修改原对象

addPortIconBtn(index) {
  // 用  JSON.parse(JSON.stringify(xxx)) 拷贝一个新的对象
  const arr = JSON.parse(JSON.stringify(this.state.machineListData))

  arr[(this.state.current - 1) * 10 + index].iscreateport = true;
  this.setState({
    machineListData: arr
  });
}

展开运算符只会拷贝第一层,也就是,你这里只拷贝了第一层对象,第二层对象的属性没有拷贝

let arr = [...this.state.machineListData]
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 求助!react 改变(浅拷贝)数组对象的某一个值,列表没有自动更新? https://www.jkxiazai.com/1568.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务