React如何阻断render刷新
使用 React.memo 进行组件记忆
React.memo 是一个高阶组件,用于对函数组件进行浅比较。当组件的 props 没有变化时,React.memo 会阻止组件重新渲染。
const MyComponent = React.memo(function MyComponent(props) {
// 组件逻辑
});
使用 useMemo 缓存计算结果
useMemo 可以缓存计算结果,只有当依赖项发生变化时才重新计算。这可以避免不必要的计算和渲染。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
使用 useCallback 缓存回调函数
useCallback 可以缓存回调函数,防止因为回调函数引用变化导致的子组件不必要渲染。
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
实现 shouldComponentUpdate
在类组件中,可以通过实现 shouldComponentUpdate 生命周期方法来控制组件是否需要更新。
class MyComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// 自定义比较逻辑
return this.props.value !== nextProps.value;
}
render() {
return <div>{this.props.value}</div>;
}
}
使用 PureComponent
PureComponent 会自动对 props 和 state 进行浅比较,如果没变化则不会重新渲染。
class MyComponent extends React.PureComponent {
render() {
return <div>{this.props.value}</div>;
}
}
避免在 render 方法中创建新对象
在 render 方法中创建新对象或数组会导致子组件每次都被重新渲染,应该将这些对象提取到组件外部或使用 useMemo。
使用不可变数据
使用不可变数据可以更容易地比较数据是否发生变化,从而优化渲染性能。可以使用 Immutable.js 等库来帮助管理不可变数据。
拆分大型组件
将大型组件拆分为多个小组件,每个小组件可以独立决定是否需要更新,这样可以减少不必要的渲染。
使用 Context 谨慎
Context 的变化会导致所有消费该 Context 的组件重新渲染,应该将 Context 的值拆分为多个小 Context 或使用 memo 优化消费组件。

使用 React 开发者工具分析
使用 React Developer Tools 的 Profiler 功能可以分析组件渲染情况,找出不必要的渲染并进行优化。






