gpt4 book ai didi

javascript - PureComponent 如何工作?

转载 作者:行者123 更新时间:2023-11-29 11:01:45 25 4
gpt4 key购买 nike

我的理解是 PureComponent 利用 shouldComponentUpdate() 并对状态和 props 进行浅层比较,但我创建了一个运行方式与我预期不同的小示例。

示例应用程序显示人员列表。每个列表项都可以更改其名称。尝试一下并检查代码 here .

在父组件中,我有一个如下所示的方法:

  updateName(id, newName) {
const { people } = this.state
const idx = people.findIndex(person => person.id === id)

people[idx].name = newName
this.setState({ people })
}

我传递回 setState 的对象与前一个对象具有相同的引用。在这种情况下,如果该组件正在进行浅比较,它不应该不更新吗?

其次,另一部分不清楚,我将子组件 Person 从 PureComponent 更改为 Component 并且我仍然只获得更新重新渲染的子组件的好处(我正在做如果您想检查每个子渲染器的控制台日志)。显然,这是 React 在内部为子组件决定是否应该更新的事情,但我假设如果组件正在重新渲染,它会重新渲染所有内容。

最佳答案

shouldn't this component not update if it's doing a shallow comparison?

是的。而且它没有更新。您可以看到 App 组件的 render() 方法在初始渲染后没有被再次调用。这意味着浅层比较如您预期的那样工作,并且组件(正确地)没有更新。

我相信让您失望的部分是 Person.prototype.handleSubmit() 中的这一行:

this.setState({ value: '' })

因为 oldState.value !== newState.value,这将触发修改后的 Person 组件的重新渲染,无论 Person 是否为 PureComponent

如果您删除此行,您将看到没有任何更新(您期望的行为)。

Clearly this is something that React is doing internally to decide for the child whether it should update.

不, child 正在设置自己的状态。父子关系在这里无关紧要。 React 将直接更新 child 。

将来您应该尝试隔离您的测试。出现这种混淆的原因是因为您依赖于 render() 方法来确定 child 是否收到了新 Prop 。但是 render() 方法会在 child 接收到新 Prop 时以及 child 设置新状态时被调用。

对这种情况更好的测试是检查 componentWillReceiveProps() 是否被调用,从而从图片中消除 state:

componentWillReceiveProps(newProps) {
console.log('receiving props', newProps)
}

如果将它插入 Person 组件,您会发现它没有被调用。完全符合您的预期。

简而言之,React.PureComponent 完全按照您的想法工作。

关于javascript - PureComponent 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45821086/

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