🚀 React网络请求时机的奇妙旅程
🌍 网络请求:组件的"外卖订餐"
想象React组件是一个家庭,而发起网络请求就像订外卖。那么问题来了:什么时候打电话订餐最合适?
🏠 类组件中的请求时机
1️⃣ componentDidMount:完美时机
生活类比: 这就像搬入新家后才订外卖。房子已经准备好了,家具都摆放好了,现在正是点外卖的最佳时机!
class WeatherDashboard extends React.Component {
constructor(props) {
super(props);
this.state = { temperature: null, isLoading: true };
// 🛑 不要在这里发请求!家具还没摆好呢!
}
componentDidMount() {
// ✅ 完美时机!DOM已准备好,组件已挂载
fetch('https://weather-api.example.com/current')
.then(response => response.json())
.then(data => {
this.setState({
temperature: data.temperature,
isLoading: false
});
})
.catch(error => {
console.error('天气加载失败', error);
this.setState({ isLoading: false });
});
}
render() {
const { temperature, isLoading } = this.state;
return (
<div>
{isLoading ? (
<p>正在加载天气数据...</p>
) : (
<p>当前温度: {temperature}°C</p>
)}
</div>
);
}
}
要点:
- 组件已完全挂载到DOM
- 可以安全地进行状态更新
- 用户已看到初始UI,可以显示加载状态