有时我们需要通过跳过一些效果来优化性能。
在某些情况下,在每次渲染后清理或应用效果可能会产生性能问题。在类组件中,我们可以通过在 componentDidUpdate 中编写与 prevProps 或 prevState 的额外比较来解决这个问题:
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
document.title = `You clicked ${this.state.count} times`;
}
}
这个要求很常见,它内置在 useEffect Hook API 中。如果某些值在重新渲染之间没有改变,你可以告诉 React 跳过应用效果。为此,请将数组作为可选的第二个参数传递给 useEffect:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
在上面的示例中,我们将 [count] 作为第二个参数传递。这是什么意思?如果 count 是 5,然后我们的组件重新渲染 count 仍然等于 5,React 将比较前一次渲染的 [5] 和下一次渲染的 [5]。因为数组中的所有项都是相同的(5 === 5),所以 React 会跳过这个效果。这就是我们的优化。
当我们将计数更新为 6 进行渲染时,React 会将前一次渲染中的 [5] 数组中的项目与下一次渲染中的 [6] 数组中的项目进行比较。这一次,React 将重新应用效果,因为 5 !== 6。如果数组中有多个项目,即使其中一个不同,React 也会重新运行效果。
这也适用于具有清理阶段的效果:
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
}, [props.friend.id]); // Only re-subscribe if props.friend.id changes