MST

星途 面试题库

面试题:React 中 getDerivedStateFromProps 如何根据 props 更新 state

请解释在 React 组件中,`getDerivedStateFromProps` 方法是如何根据传入的 `props` 来更新 `state` 的,并举例说明常见的使用场景。
42.0万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

getDerivedStateFromProps 方法更新 state 的原理

getDerivedStateFromProps 是 React 组件的静态方法,它在组件实例化之后,每次接收到新的 props 时都会被调用。其语法为:

static getDerivedStateFromProps(props, state) {
  // 逻辑判断,根据props返回新的state,若不需要更新则返回null
  if (props.someValue!== state.someValue) {
    return { someValue: props.someValue };
  }
  return null;
}

它接收两个参数,props 是最新传入的属性,state 是当前的状态。该方法应该返回一个对象来更新状态,如果不需要更新则返回 null。通过比较新的 props 和当前的 state,我们可以决定是否需要更新 state

常见使用场景举例

  1. 根据 props 初始化 state 假设我们有一个 Counter 组件,它接收一个初始值 initialCount 作为 props,我们可以使用 getDerivedStateFromProps 来初始化 state 中的 count
import React, { Component } from'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  static getDerivedStateFromProps(props, state) {
    if (!state.initialized) {
      return {
        count: props.initialCount,
        initialized: true
      };
    }
    return null;
  }
  render() {
    return <div>{this.state.count}</div>;
  }
}
  1. 根据 props 更新 state 假设有一个 Image 组件,它接收 src 属性,当 src 变化时,我们需要更新 state 中的 imageLoaded 状态来表示图片是否加载完成。
import React, { Component } from'react';

class Image extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imageLoaded: false
    };
  }
  static getDerivedStateFromProps(props, state) {
    if (props.src!== state.prevSrc) {
      return {
        imageLoaded: false,
        prevSrc: props.src
      };
    }
    return null;
  }
  handleImageLoad = () => {
    this.setState({ imageLoaded: true });
  };
  render() {
    return (
      <img
        src={this.props.src}
        onLoad={this.handleImageLoad}
        alt="example"
      />
    );
  }
}