react如何防止重复
防止重复渲染的常见方法
在React中防止组件不必要的重复渲染是优化性能的关键。以下是几种有效的方法:
使用React.memo进行组件记忆 React.memo是一个高阶组件,用于记忆函数组件的渲染结果。只有当props发生变化时才会重新渲染:
const MyComponent = React.memo(function MyComponent(props) {
/* 使用props渲染 */
});
合理使用useCallback和useMemo useCallback记忆回调函数,useMemo记忆计算结果,避免每次渲染都创建新的引用:
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
shouldComponentUpdate生命周期方法 在类组件中,可以通过实现shouldComponentUpdate来控制更新:
shouldComponentUpdate(nextProps, nextState) {
return nextProps.someProp !== this.props.someProp;
}
使用PureComponent PureComponent自动实现了shouldComponentUpdate的浅比较:
class MyComponent extends React.PureComponent {
render() {
return <div>{this.props.someProp}</div>;
}
}
避免在render中创建新对象/函数 直接在render中创建对象或函数会导致每次渲染都生成新的引用:
// 避免这样
render() {
return <Child style={{ color: 'red' }} onClick={() => {...}} />;
}
使用不可变数据 使用不可变数据可以更容易地检测数据变化。推荐使用immer等库:
import produce from 'immer';
const nextState = produce(currentState, draft => {
draft.pages.push('new page');
});
合理拆分组件 将经常变化的和稳定的部分拆分成不同组件,减少不必要的渲染范围:
function Parent() {
const [count, setCount] = useState(0);
return (
<>
<ExpensiveComponent />
<button onClick={() => setCount(c => c + 1)}>Count: {count}</button>
</>
);
}
使用useReducer替代多个useState 当有多个关联的状态时,useReducer可以减少状态更新次数:
const [state, dispatch] = useReducer(reducer, initialState);
避免在useEffect中触发不必要的更新 确保useEffect的依赖数组准确,避免无限循环:
useEffect(() => {
// 仅在count变化时执行
document.title = `Count: ${count}`;
}, [count]);






