React如何阻断render刷新
阻断 React 组件 render 刷新的方法
在 React 中,组件的重新渲染(re-render)通常由状态(state)或属性(props)的变化触发。以下是几种有效阻断不必要渲染的方法:
使用 React.memo 包裹组件
React.memo 是一个高阶组件,用于对函数组件进行浅比较(shallow comparison),避免在 props 未变化时重新渲染。
const MyComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
实现 shouldComponentUpdate(类组件)
在类组件中,可以通过覆盖 shouldComponentUpdate 方法手动控制渲染逻辑。

class MyComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
return nextProps.value !== this.props.value;
}
render() {
return <div>{this.props.value}</div>;
}
}
使用 useMemo 缓存计算结果
useMemo 可以缓存计算结果,避免在依赖项未变化时重复计算。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
使用 useCallback 缓存函数
useCallback 可以缓存函数引用,避免因函数引用变化导致子组件不必要的渲染。

const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
避免直接修改状态或属性
直接修改状态或属性可能导致浅比较失效,应始终使用不可变数据。
// 错误:直接修改状态
this.state.items.push(newItem);
// 正确:使用不可变更新
this.setState(prevState => ({
items: [...prevState.items, newItem]
}));
使用 Context API 的优化
当使用 Context 时,可以通过拆分 Context 或使用 useContextSelector 避免不必要的渲染。
const ThemeContext = React.createContext();
function App() {
return (
<ThemeContext.Provider value={{ theme: 'dark' }}>
<Toolbar />
</ThemeContext.Provider>
);
}
避免在渲染中创建新对象/数组
在渲染函数中创建新对象或数组会导致每次渲染都生成新的引用,触发子组件更新。
// 错误:每次渲染创建新对象
<ChildComponent style={{ color: 'red' }} />
// 正确:提取到组件外部或 useMemo
const style = useMemo(() => ({ color: 'red' }), []);
<ChildComponent style={style} />
通过合理应用这些方法,可以有效控制 React 组件的渲染行为,提升应用性能。






