面试题答案
一键面试在React中,通常在componentDidMount
生命周期函数中发起API请求。因为这个函数在组件挂载(插入到DOM)后立即调用,此时组件已经准备好,可以安全地发起网络请求。
以下是一个示例,展示如何在componentDidMount
中发起请求并处理返回数据以展示用户信息:
import React, { Component } from 'react';
class UserInfo extends Component {
constructor(props) {
super(props);
this.state = {
user: null,
loading: false,
error: null
};
}
componentDidMount() {
this.setState({ loading: true });
fetch('https://example.com/api/user')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
this.setState({ user: data, loading: false });
})
.catch(error => {
this.setState({ error, loading: false });
});
}
render() {
const { user, loading, error } = this.state;
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{user && (
<div>
<p>Name: {user.name}</p>
<p>Email: {user.email}</p>
</div>
)}
</div>
);
}
}
export default UserInfo;
在上述代码中:
componentDidMount
中发起了一个fetch
请求获取用户信息。- 在发起请求前,设置
loading
状态为true
,以显示加载状态。 - 请求成功后,将返回的数据设置到
user
状态,并将loading
设置为false
。 - 如果请求过程中出现错误,捕获错误并设置
error
状态,同时将loading
设置为false
。 - 在
render
方法中,根据不同的状态展示加载状态、错误信息或用户信息。