我有一个很深的状态结构(在下面的示例中称为myObjects
)。
此代码有效:
import set from 'lodash/set'
changeObjectProperty = (key = '', path = '', value = null) => {
const updatedMyObject = Object.assign({}, this.state.myObjects[key])
set(updatedMyObject, path, value)
const newMyObjects = Object.assign({}, this.state.myObjects, { [key]: updatedMyObject })
this.setState({ myObjects: newMyObjects })
}
...但这不是深度克隆,因此我正在重复使用引用。
如果我改用cloneDeep
:
import set from 'lodash/set'
import cloneDeep from 'lodash/cloneDeep'
changeObjectProperty = (key = '', path = '', value = null) => {
const updatedMyObject = cloneDeep(this.state.myObjects[key])
set(updatedMyObject, path, value)
const newMyObjects = Object.assign({}, this.state.myObjects, { [key]: updatedMyObject })
this.setState({ myObjects: newMyObjects })
}
...反应似乎并未注意到状态变化。为什么?
此外,文章“Handling State in React: Four Immutable Approaches to Consider” (Cory Dash on Medium.com)说:
“深度克隆会导致不必要的渲染,因为React认为一切都已更改,而实际上可能只有特定的子对象已更改。”
...所以也许首选带有浅层合并的示例1?