react 性能优化是哪个周期函数?
在 React 类组件 里,性能优化常用的生命周期函数是:
shouldComponentUpdate(nextProps, nextState)
-
作用:在组件 重新渲染前 执行,返回 true/false 来决定是否需要重新渲染。
-
默认返回 true,表示每次更新都会重新渲染。
-
通过对比 this.props / this.state 和 nextProps / nextState,可以避免不必要的重新渲染,提高性能。
示例:
class MyComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// 只有当某个 props 改变时才重新渲染
return nextProps.value !== this.props.value;
}
render() {
console.log("渲染了");
return <div>{this.props.value}</div>;
}
}
在 函数组件 中
没有生命周期函数,但有对应的优化方法:
-
React.memo:类似于 shouldComponentUpdate,包裹函数组件,只有 props 变化时才重新渲染。
-
useMemo:缓存计算结果,避免重复计算。
-
useCallback:缓存函数,避免子组件重复渲染。
const MyComponent = React.memo(({ value }) => {
console.log("渲染了");
return <div>{value}</div>;
});
总结:
-
类组件 → shouldComponentUpdate
-
函数组件 → React.memo + useMemo + useCallback
浙公网安备 33010602011771号