使用Object.assign和Lodash cloneDeep对setState进行深度嵌套反应

时间:2018-10-15 13:13:35

标签: javascript reactjs lodash

我有一个很深的状态结构(在下面的示例中称为myObjects)。

此代码有效:

示例1(Object.assign)

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 })
}

...但这不是深度克隆,因此我正在重复使用引用。

示例2(cloneDeep)

如果我改用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?

0 个答案:

没有答案