在 redux
中,如果您的 action
/reducer
更新了 foo.bar
的值以及连接组件的 mapStateToProps
是 (store) => { foo: store.foo }
,然后将 foo={foo}
传递给 PureComponent
child 。当 foo.bar
改变时,子进程不会重新渲染?这就是为什么他们建议让事情尽可能平坦?
感谢您的澄清。
最佳答案
有两个问题:
- 一般来说,
PureComponent
实例何时更新? - 此示例中的
PureComponent
组件实例是否更新?
问题#1:PureComponent
对 shouldComponentUpdate
中的 props 进行浅层比较。 this question 的答案中很好地描述了这意味着什么。 。总而言之,浅层比较检查引用相等而不是值相等。因此,如果 lastProps.myObj
和 nextProps.myObj
都是对同一对象的引用,则浅比较的计算结果为 true
,即使 lastProps.myObj.foo
和 nextProps.myObj.foo
不相等。
问题#2:如果您更改了 state.foo
,使其成为具有更改值的同一对象,则浅比较将返回假阴性。这里的复杂因素是您的示例使用 Redux。您说 Redux reducer 已更改 state.foo
。第一个rules Redux reducer 的一个特点是它们不会改变状态或属性。他们返回一个新的状态。当状态是一个对象时,它们会创建该对象的副本并将更改应用于该副本。如果您遵守 reducer 契约并更新状态而不改变它,那么您已经更改了引用。在这种情况下,PureComponent.prototype.shouldComponentUpdate
应返回 true
。
// create an object
var foo = {bar: 'bar'};
// make a copy of the object
var bar = Object.assign({}, foo);
// both objects look the same, i.e. have the same property with an equal value
foo.bar === bar.bar // -> true
// but they are not the same object so the shallow comparison evaluates to false
foo === bar // -> false
因此,如果 PureComponent
实例在 state.foo
更改时没有更新,我会检查更改 foo
的 reducer 并确保更新不是突变。
关于javascript - 如果 redux 更新了嵌套组件,但 PureComponent 作为 prop 传递给了它的父组件,那么 PureComponent 会重新渲染吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45017129/