面试题答案
一键面试- React 组件生命周期方法执行顺序:
- 挂载阶段:
constructor
:组件构造函数,在创建组件实例时最先调用,用于初始化状态和绑定方法等。getDerivedStateFromProps
:在调用render
方法之前调用,并且在初始化挂载及后续更新时都会被调用,可根据props
来更新state
。render
:是必须实现的方法,用于描述组件的 UI 结构,此方法不能修改状态和 DOM 操作。componentDidMount
:组件挂载到 DOM 后调用,适合进行副作用操作,如发起网络请求、添加事件监听器等。
- 更新阶段:
getDerivedStateFromProps
:同挂载阶段,在更新时也会调用,根据新的props
更新state
。shouldComponentUpdate
:在接收到新的props
或state
时调用,返回一个布尔值,决定组件是否需要更新,返回false
可阻止不必要的更新。render
:同挂载阶段,再次渲染组件 UI。getSnapshotBeforeUpdate
:在render
之后,componentDidUpdate
之前调用,可用于获取 DOM 更新前的快照,如滚动位置等。componentDidUpdate
:组件更新完成后调用,可在此处进行依赖于 DOM 更新后的操作,如操作更新后的 DOM,对比更新前后的props
和state
等。
- 卸载阶段:
componentWillUnmount
:组件从 DOM 中移除前调用,可在此处进行清理操作,如取消网络请求、移除事件监听器等。
- 挂载阶段:
- 适合数据初始化操作的生命周期方法:
constructor
:适合进行一些简单的数据初始化,比如设置初始状态this.state = { data: [] };
以及绑定事件处理函数this.handleClick = this.handleClick.bind(this);
等。
例如:
import React, { Component } from'react';
class MyComponent extends 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 (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
export default MyComponent;
在这个例子中,在 constructor
里初始化了 count
状态,并绑定了 handleClick
方法。