MST

星途 面试题库

面试题:React列表渲染性能优化之shouldComponentUpdate与PureComponent

当一个包含大量列表项的React组件频繁更新时,会导致性能问题。请描述如何通过shouldComponentUpdate生命周期方法或PureComponent来优化性能。假设列表项是简单的数据展示组件,在数据变化时,如何确保不必要的重新渲染被避免,给出具体的实现思路和代码示例。
37.5万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

1. 使用 shouldComponentUpdate

  • 实现思路
    • shouldComponentUpdate 是 React 组件的生命周期方法,它接收 nextPropsnextState 作为参数。
    • 在这个方法中,我们可以对比当前的 propsstate 与即将更新的 nextPropsnextState。如果数据没有变化,就返回 false,阻止组件重新渲染;如果数据有变化,返回 true,允许组件重新渲染。
    • 对于包含大量列表项的组件,由于列表项是简单的数据展示组件,我们主要关注 props 的变化。如果列表项的数据(作为 props 传递)没有改变,就阻止列表项重新渲染。
  • 代码示例
import React from 'react';

class ListItem extends React.Component {
    shouldComponentUpdate(nextProps) {
        // 这里假设列表项的数据只在text属性上
        return this.props.text!== nextProps.text;
    }
    render() {
        return <div>{this.props.text}</div>;
    }
}

class List extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: ['item1', 'item2', 'item3']
        };
    }
    handleUpdate = () => {
        // 这里模拟更新操作
        this.setState({
            list: ['item1', 'item2', 'item4']
        });
    }
    render() {
        return (
            <div>
                <button onClick={this.handleUpdate}>Update List</button>
                {this.state.list.map((text, index) => (
                    <ListItem key={index} text={text} />
                ))}
            </div>
        );
    }
}

export default List;

2. 使用 PureComponent

  • 实现思路
    • PureComponent 是 React 提供的一个基类,它会自动实现一个浅比较的 shouldComponentUpdate 方法。
    • 当组件的 propsstate 发生变化时,PureComponent 会对新的 propsstate 与之前的进行浅比较。如果所有的嵌套对象和数组的引用都没有改变,就不会重新渲染组件。
    • 对于简单的数据展示列表项组件,只要传递给它的 props 引用没有变化,就不会重新渲染。
  • 代码示例
import React from 'react';

class List extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: ['item1', 'item2', 'item3']
        };
    }
    handleUpdate = () => {
        // 这里模拟更新操作,注意要创建新的数组引用
        const newList = [...this.state.list];
        newList[2] = 'item4';
        this.setState({
            list: newList
        });
    }
    render() {
        return (
            <div>
                <button onClick={this.handleUpdate}>Update List</button>
                {this.state.list.map((text, index) => (
                    <PureListItem key={index} text={text} />
                ))}
            </div>
        );
    }
}

class PureListItem extends React.PureComponent {
    render() {
        return <div>{this.props.text}</div>;
    }
}

export default List;

在实际应用中,如果数据结构比较复杂,浅比较可能无法满足需求,此时可能需要使用更复杂的比较逻辑(如深比较)在 shouldComponentUpdate 中,而 PureComponent 的浅比较就不太适用了。但对于简单的数据展示列表项,上述两种方法能有效优化性能。