4

如何避免 React 组件重渲染的方法

 1 year ago
source link: https://www.51cto.com/article/751240.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何避免 React 组件重渲染的方法

作者:NativeBase 2023-04-06 09:41:00
在 ShouldComponentUpdate 或 PureComponent 中进行 Props 和State 的浅比较,如果没有变化,则返回 False,防止不必要的重渲染。
a7efd6935b609cdef03051692390426a8d4e85.png

React 组件重渲染可能会导致应用性能下降,以下是一些避免重渲染的方法和实战经验:

1、使用 shouldComponentUpdate 或 PureComponent

在 shouldComponentUpdate 或 PureComponent 中进行 props 和 state 的浅比较,如果没有变化,则返回 false,防止不必要的重渲染。

2、使用 React.memo

对于函数组件,可以使用 React.memo 高阶组件对组件的 props 进行浅比较,如果没有变化,则返回缓存的组件。

const MyComponent = React.memo((props) => {
  // ...
});

3、使用 useMemo 和 useCallback

对于需要传递给子组件的 props,可以使用 useMemo 缓存计算结果,避免在每次渲染时重新计算。

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

对于需要传递给子组件的回调函数,可以使用 useCallback 缓存函数实例,避免在每次渲染时重新创建函数实例。

const handleClick = useCallback(() => {
  // ...
}, [a, b]);

4、避免更新整个 state

在使用 setState 更新 state 时,确保只更新必要的部分,而不是整个 state 对象。例如,如果只需要更新 state 中的一个属性,可以使用对象的展开语法:

this.setState({ count: this.state.count + 1 });

5、避免在 render 方法中创建新的对象或数组

在 render 方法中创建新的对象或数组会导致组件重渲染,可以将它们提取到组件外部的变量中。

const options = [{ value: 'foo', label: 'Foo' }, { value: 'bar', label: 'Bar' }];

function MyComponent() {
  return <Select optinotallow={options} />;
}

6、避免在 render 方法中执行耗时的操作

在 render 方法中执行耗时的操作会导致组件重渲染,可以将它们提前到组件的生命周期方法中执行。

class MyComponent extends React.Component {
  componentDidMount() {
    // 执行耗时操作
  }

  render() {
    // ...
  }
}

以上是一些避免 React 组件重渲染的方法和实战经验,可以根据具体情况选择合适的方法来优化应用性能。

责任编辑:姜华 来源: 今日头条

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK