面试题答案
一键面试- 在
componentDidMount
中发起异步请求并设置状态流程:- 首先,在
componentDidMount
生命周期方法内使用fetch
发起异步请求。例如:
- 首先,在
import React, { Component } from'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
fetch('your - api - url')
.then(response => response.json())
.then(data => {
this.setState({
data: data
});
});
}
render() {
return (
<div>
{this.state.data? <p>{JSON.stringify(this.state.data)}</p> : <p>Loading...</p>}
</div>
);
}
}
export default MyComponent;
- 这里
fetch
返回一个Promise,通过.then
链式调用处理响应数据,将解析后的数据使用setState
设置到组件状态this.state.data
。
- 处理异步操作未完成时组件卸载避免
setState
错误:- 可以在组件中定义一个标识变量,例如
isMounted
,在componentDidMount
中初始化为true
,在componentWillUnmount
中将其设置为false
。 - 在
fetch
的.then
回调中,先检查isMounted
,如果为true
再执行setState
。修改后的代码如下:
- 可以在组件中定义一个标识变量,例如
import React, { Component } from'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
this.isMounted = false;
}
componentDidMount() {
this.isMounted = true;
fetch('your - api - url')
.then(response => response.json())
.then(data => {
if (this.isMounted) {
this.setState({
data: data
});
}
});
}
componentWillUnmount() {
this.isMounted = false;
}
render() {
return (
<div>
{this.state.data? <p>{JSON.stringify(this.state.data)}</p> : <p>Loading...</p>}
</div>
);
}
}
export default MyComponent;
这样,当组件在异步操作未完成时卸载,isMounted
会变为false
,从而避免在已卸载的组件上执行setState
导致的错误。