MST

星途 面试题库

面试题:React组件加载阶段生命周期方法的调用顺序及用途

请详细说明React组件加载阶段(mounting)生命周期方法`constructor`、`getDerivedStateFromProps`、`render`、`componentDidMount`的调用顺序,并简述每个方法的主要用途。
39.8万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
  1. 调用顺序constructor -> getDerivedStateFromProps -> render -> componentDidMount

  2. 各方法主要用途

    • constructor
      • 用途:在创建组件实例后立即调用。主要用于初始化组件的 state,可以绑定事件处理函数到实例。例如:
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({ count: this.state.count + 1 });
    }
    render() {
        return <button onClick={this.handleClick}>Click me: {this.state.count}</button>;
    }
}
  • getDerivedStateFromProps
    • 用途:这是一个静态方法,会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它接收 propsstate 作为参数,返回一个对象来更新 state,或者返回 null 表示不需要更新 state。主要用于根据 props 的变化来更新 state。例如:
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { value: props.initialValue };
    }
    static getDerivedStateFromProps(props, state) {
        if (props.initialValue!== state.value) {
            return { value: props.initialValue };
        }
        return null;
    }
    render() {
        return <div>{this.state.value}</div>;
    }
}
  • render
    • 用途:是组件中唯一必需的方法。它根据组件的 stateprops 返回一个 React 元素(可以是原生 DOM 元素,也可以是自定义组件),描述了该组件在页面上应呈现的内容。例如:
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { message: 'Hello' };
    }
    render() {
        return <div>{this.state.message}</div>;
    }
}
  • componentDidMount
    • 用途:在组件被插入到 DOM 后立即调用。常用于需要访问 DOM 节点、发起网络请求、添加订阅等操作。例如:
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { data: null };
    }
    componentDidMount() {
        fetch('https://example.com/api/data')
          .then(response => response.json())
          .then(data => this.setState({ data }));
    }
    render() {
        return <div>{this.state.data? JSON.stringify(this.state.data) : 'Loading...'}</div>;
    }
}