简体   繁体   中英

Cannot assign to read only property of #<Object> using React with Recoil

I'm trying to update my state (an array of objects), but get the above error whenever I try to use.map or edit a clone of the state object.

  React.useEffect(() => {
setUserMeasurements((oldUserMeasurements) => {
  return oldUserMeasurements.map(nameAndMeasure => {
    if (nameAndMeasure.name === name) { nameAndMeasure.measure = 60 }
    return nameAndMeasure;
  })
})

})

It doesn't seem to like it when I try the "nameAndMeasure.measure = 60" section of code, but I can't understand why. Can anyone explain?

I found that I could use this function to do what I was trying to get.map to do:

function replaceItemAtIndex(arr, index, newValue) {  return [...arr.slice(0, index), newValue, ...arr.slice(index + 1)]; }

The.slice methods seem to create a new array, which satisfies javascript in a way that.map doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM