
React 組件重渲染可能會(huì)導(dǎo)致應(yīng)用性能下降,以下是一些避免重渲染的方法和實(shí)戰(zhàn)經(jīng)驗(yàn):
1.使用 shouldComponentUpdate 或 PureComponent
在 shouldComponentUpdate 或 PureComponent 中進(jìn)行 props 和 state 的淺比較,如果沒有變化,則返回 false,防止不必要的重渲染。
- 使用 React.memo
對(duì)于函數(shù)組件,可以使用 React.memo 高階組件對(duì)組件的 props 進(jìn)行淺比較,如果沒有變化,則返回緩存的組件。
const MyComponent = React.memo((props) => {
// ...
});
- 使用 useMemo 和 useCallback
對(duì)于需要傳遞給子組件的 props,可以使用 useMemo 緩存計(jì)算結(jié)果,避免在每次渲染時(shí)重新計(jì)算。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
對(duì)于需要傳遞給子組件的回調(diào)函數(shù),可以使用 useCallback 緩存函數(shù)實(shí)例,避免在每次渲染時(shí)重新創(chuàng)建函數(shù)實(shí)例。
const handleClick = useCallback(() => {
// ...
}, [a, b]);
- 避免更新整個(gè) state
在使用 setState 更新 state 時(shí),確保只更新必要的部分,而不是整個(gè) state 對(duì)象。例如,如果只需要更新 state 中的一個(gè)屬性,可以使用對(duì)象的展開語法:
this.setState({ count: this.state.count + 1 });
- 避免在 render 方法中創(chuàng)建新的對(duì)象或數(shù)組
在 render 方法中創(chuàng)建新的對(duì)象或數(shù)組會(huì)導(dǎo)致組件重渲染,可以將它們提取到組件外部的變量中。
const options = [{ value: 'foo', label: 'Foo' }, { value: 'bar', label: 'Bar' }];
function MyComponent() {
return <Select options={options} />;
}
- 避免在 render 方法中執(zhí)行耗時(shí)的操作
在 render 方法中執(zhí)行耗時(shí)的操作會(huì)導(dǎo)致組件重渲染,可以將它們提前到組件的生命周期方法中執(zhí)行。
class MyComponent extends React.Component {
componentDidMount() {
// 執(zhí)行耗時(shí)操作
}
render() {
// ...
}
}
以上是一些避免 React 組件重渲染的方法和實(shí)戰(zhàn)經(jīng)驗(yàn),可以根據(jù)具體情況選擇合適的方法來優(yōu)化應(yīng)用性能。






