gpt4 book ai didi

javascript - 如果 redux 更新了一个嵌套组件,但是 PureComponent 作为 prop 传递给它的父组件,PureComponent 会重新渲染吗?

转载 作者:行者123 更新时间:2023-11-29 21:03:59 26 4
gpt4 key购买 nike

redux 中,如果您的 action/reducer 更新了 foo.bar 的值和您连接的组件的 mapStateToProps(store) => { foo: store.foo } 然后将 foo={foo} 传递给 PureComponent child 。当 foo.bar 更改时, child 不会重新呈现?这就是为什么他们建议尽可能保持平坦?

感谢您的澄清。

最佳答案

有两个问题:

  1. 通常,PureComponent 实例何时更新?
  2. 此示例中的 PureComponent 组件实例是否正在更新?

问题 #1:PureComponentshouldComponentUpdate 中的 props 进行了浅层比较。 this question 的答案中很好地描述了这意味着什么.总而言之,浅层比较检查引用的相等性而不是值的相等性。因此,如果 lastProps.myObjnextProps.myObj 都是对同一对象的引用,浅比较的计算结果为 true,即使 lastProps.myObj.foonextProps.myObj.foo 不相等。

问题 #2:如果您更改了 state.foo,使其成为具有更改值的同一对象,那么浅层比较将返回假阴性。这里的复杂因素是您的示例使用 Redux。你说 Redux reducer 改变了 state.foo。第一个rules Redux reducers 的优点在于它们不会改变 state 或 props。他们返回一个新的状态。当 state 是一个对象时,他们会复制该对象并将更改应用于该副本。如果您遵守 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

因此,如果 state.foo 更改时 PureComponent 实例未更新,我将检查更改 foo 的 reducer 并确保更新不是突变。

关于javascript - 如果 redux 更新了一个嵌套组件,但是 PureComponent 作为 prop 传递给它的父组件,PureComponent 会重新渲染吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45017129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com