【问题标题】:Make a copy of array State in react hook在反应钩子中复制数组状态
【发布时间】:2021-10-02 09:28:02
【问题描述】:

你好,我正在使用如下更新功能:

const [listLockerUserType, setListLockerUserTypes] = useState([])

const getData = (content) => {
        let contentLocker = {...content}
        let keys = Object.keys(contentLocker)
        const listLocker = [...listLockerUserType]
         let index = listLocker.findIndex(item => item.userTypeId == content.id)
         listLocker[index][`${keys[1}`] = content[`${keys[1]}`]
         setListLockerUserTypes(listLocker)
        console.log(content)
      }

但是当我这样做时,它会给我一个错误

TypeError: Cannot assign to read only property 'description' of object '#<Object>'

description 是 listLockerUserType 对象的属性。请给我一个提示!非常感谢你!!

【问题讨论】:

  • 请问你为什么将listLockerUserType复制到listLocker中?
  • @novonimo 实际上 listLockerUserType 是从我的 api 获取的,我想更新 listLockerUserType 中的数据,当用户单击提交时,我将调用 api update
  • 但是你可以在没有副本的情况下做到这一点,使用像 map() 和 filter() 这样的高阶函数。你试过这个吗?

标签: reactjs state deep-copy


【解决方案1】:

我发现解决方案只是改变

const listLocker = [...listLockerUserType]

let listLocker = JSON.parse(JSON.stringify(listLockerUserType))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2021-05-19
    • 2021-10-12
    • 2020-10-23
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多