将数据保存到Redux工具包后,useState变为只读

z0qdvdin  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(84)

将useState推送到redux工具包后,将报告setState错误Uncatched TypeError:无法指派给对象'#'的只读属性'name'
第一个
点击提交后,点击ChangeName后出错,点击提交前没有错误
错误:未捕获TypeError:无法指派给对象'#'的只读属性'name'
我尝试修改setState和changeNameArr的写入方法,但它们不起作用或报告错误
第一次
刚进入页面时可以正常执行此方法,但保存数据到Redux工具包后,无法再次执行此方法
我希望你能帮我解决这个问题

jei2mxaa

jei2mxaa1#

Redux状态和React状态都应始终作为只读状态处理-您应始终创建带有更改的副本,而不要更改原始状态。
您的代码在这里,

let temp = arr
 arr.push({name:2})

不会建立arr的复本。
它创建了一个新的变量temp指向arr。不管你是否执行temp.pusharr.push,你都改变了。
通常情况下,这种情况不会出现(直到后来它变成一个非常微妙的bug),但由于您将相同的引用放入Redux(Redux会采取措施防止意外突变),您现在注意到了它-该更改不仅会更改temparr,还会更改Redux的状态。
因此,实际上,您必须创建一个新副本,而不是仅推送:

setArr(prev => [...prev, {name: 2}])

setArr(prev => {
  const next = [...prev] // create a new array as a shallow copy, not a reference. All the objects *inside* that array are still references to the old array elements, but the array itself is new and you can now add new elements
  next.push({name: 2}) // now you can push because it is not state anywhere yet
  return next // return it - now it becomes state and you should not modify it any more
})

相关问题