面试题答案
一键面试-
调用顺序:
constructor
->getDerivedStateFromProps
->render
->componentDidMount
-
各方法主要用途:
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
方法之前调用,并且在初始挂载及后续更新时都会被调用。它接收props
和state
作为参数,返回一个对象来更新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
:- 用途:是组件中唯一必需的方法。它根据组件的
state
和props
返回一个 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>;
}
}