state中数据如下

this.state = {
  pageNav: {
    pageSize: 20,
    pageNum: 1,
    total: 50
  }
}

举例:只修改state中的total的值为100

错误方法:
// 如此做法,pageNav对象的属性全部替换为只有total一个属性,其它属性丢失。

// 熟悉vue,因为有数据绑定,其它属性值并不会丢失。因为使用react没多久,特此将自己的错误记录下  
this.setState({
    pageNav: {
        total: 100
        }
})

正确方法:

let pageNav = this.state.pageNav;
pageNav.total = 100;
this.setState({
    pageNav
})

批量修改多属性:

let obj =  {
  total: Number(res.data.total),
  pageSize: Number(res.data.size),
  current: Number(res.data.current),
}
let pageNav = Object.assign(this.state.pageNav,obj)
this.setState({
    pageNav
})

原文链接:https://blog.csdn.net/Wcharle...

进阶(修改state某json数组的某项的某个属性)

进阶一:

转载于https://blog.csdn.net/weixin_...

this.state = {
    listData: [
        {name: "小坏", age: "20"},
        {name: "小不", age: "21"},
    ]
}
change = (index) => {
    const listData = [...this.state.listData];   //复制数组--浅拷贝
    this.setState({
        listData: listData.map((item, idx) => idx === index ? {...item, name:  "陈小坏"} : item)                     
    })
}

进阶二:

this.state = {
    listData: [
        {name: "严光旺", age: {"青少年":18}},
        {name: "小不", age: "21"},
    ],
}

期望:

 listData: [
    {name: "严光旺", age: {"中老年人":30}},
    {name: "小不", age: "21"},
],

解决方案:

// index是0,要改的项的索引
change = (index) => {
    const listData = [...this.state.listData];   //复制数组--浅拷贝
    let age={"中老年人":30}
    this.setState({
        listData: listData.map((item, i) => i === index ? {...item, age} : item),
    })
}

云端的日子
66 声望1 粉丝