首页 > 解决方案 > 为什么不能直接更新对象中嵌套属性的值?

问题描述

我在 React Native 中玩耍时遇到了这个错误。我不明白为什么第一个片段会引发错误,而第二个片段运行良好。

这不起作用:

let newContent = { ...oldContent }; // <-- oldContent is a 'const'
newContent.value = newValue; // <-- property at 'root level' can be modified
newContent.nested.a = b; // <-- throws 'You attempted to set the key with the value on an object that is meant to be immutable and has been frozen.' 

但这很好用:

let newContent = { ...oldContent };
newContent.value = newValue;
newContent.nested = {
   a: b,
}

的值nested.a定义在 上oldContent

这是预期的行为还是我在第一个片段中做错了什么?

标签: javascriptreact-native

解决方案


推荐阅读