MST

星途 面试题库

面试题:React中Props的动态更新与性能优化

假设父组件中有一个状态数据stateValue,通过Props传递给子组件。当stateValue频繁变化时,如何确保子组件在更新Props时的性能最优?请从shouldComponentUpdate、PureComponent、React.memo等角度进行阐述,并给出具体实现代码。
17.9万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

1. shouldComponentUpdate

shouldComponentUpdate 是 React 类组件的生命周期方法,通过返回 truefalse 来决定组件是否需要更新。可以在该方法中对比新旧 props,只有当 props 真正发生变化时才返回 true 进行更新,从而提高性能。

import React, { Component } from 'react';

class ChildComponent extends Component {
  shouldComponentUpdate(nextProps) {
    // 对比新旧 props 中的 stateValue
    return this.props.stateValue!== nextProps.stateValue;
  }

  render() {
    return <div>{this.props.stateValue}</div>;
  }
}

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      stateValue: 0
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      stateValue: prevState.stateValue + 1
    }));
  }

  render() {
    return (
      <div>
        <ChildComponent stateValue={this.state.stateValue} />
        <button onClick={this.handleClick}>Update stateValue</button>
      </div>
    );
  }
}

export default ParentComponent;

2. PureComponent

PureComponent 是 React 提供的一个基类,它内部自动实现了 shouldComponentUpdate 方法,会对 propsstate 进行浅比较(shallow comparison)。如果 propsstate 的引用没有变化,组件不会更新。

import React, { PureComponent } from 'react';

class ChildComponent extends PureComponent {
  render() {
    return <div>{this.props.stateValue}</div>;
  }
}

class ParentComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      stateValue: 0
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      stateValue: prevState.stateValue + 1
    }));
  }

  render() {
    return (
      <div>
        <ChildComponent stateValue={this.state.stateValue} />
        <button onClick={this.handleClick}>Update stateValue</button>
      </div>
    );
  }
}

export default ParentComponent;

3. React.memo

React.memo 是一个高阶组件(HOC),用于函数式组件,和 PureComponent 类似,它会对 props 进行浅比较。如果 props 没有变化,组件不会重新渲染。

import React from'react';

const ChildComponent = React.memo(({ stateValue }) => {
  return <div>{stateValue}</div>;
});

const ParentComponent = () => {
  const [stateValue, setstateValue] = React.useState(0);
  const handleClick = () => {
    setstateValue(prevValue => prevValue + 1);
  };

  return (
    <div>
      <ChildComponent stateValue={stateValue} />
      <button onClick={handleClick}>Update stateValue</button>
    </div>
  );
};

export default ParentComponent;

总结:

  • shouldComponentUpdate 适用于类组件,开发者可以自定义对比逻辑,灵活性较高。
  • PureComponent 同样适用于类组件,自动进行浅比较,使用简单,但如果 propsstate 中有复杂数据结构可能出现问题。
  • React.memo 用于函数式组件,自动浅比较 props,使用方便,同样在处理复杂数据结构时需注意浅比较的局限性。