正如 KuchBhi 所说,您需要使用shouldComponentUpdate
生命周期方法。
shouldComponentUpdate
每当新的 props 或 state 传递给组件时都会调用它,默认情况下返回 true(可能只为更新的 props 返回 true,而不是 100% 确定)。该方法接受两个参数:nextProps
和nextState
。然后,您可以将它们与 this.props 和 this.state 进行比较,以决定是否应该更新。
此方法的默认/典型实现类似于此(伪):
shouldComponentUpdate(nextProps, nextState) {
//Really it's a deeper equality check, not just the props/state object
return this.props !== nextProps || this.state !== nextState;
}
作为替代方案,您可以在返回 false 的情况下进一步构建它。这是我的一个项目中的一个示例,我只想在两个特定道具不同时重新渲染:
shouldComponentUpdate(nextProps) {
const minUpdated = this.props.min !== nextProps.min;
const maxUpdated = this.props.max !== nextProps.max;
return minUpdated || maxUpdated;
}
该组件还具有诸如缩放、对齐、宽度等道具,但是当我收到这些作为新道具时我不想更新,所以我不检查它们是否不相等。
您基本上可以在此方法中返回 false 并且在初始加载后从不更新,但我会避免这种情况,因为它违背了反应的目的。
编辑:正如 varoons 所说,这可能是您使用新上下文 API 的绝佳场景,我强烈建议您研究一下,但了解组件生命周期方法也很有用。