在useEffect中fetch数据后设置变量出现undefined问题求助
问题原因及解决方法
核心问题1:异步请求未正确处理
你直接把fetch返回的Promise赋值给了data,此时data并不是接口返回的实际数据,而是未完成的Promise对象。而且没有在异步回调里更新state,导致setWeather拿到的是无效值。
核心问题2:React setState的异步特性
setWeather是异步执行的,调用后立刻console.log(weather.data),此时组件state还没完成更新,所以会输出undefined。
修正后的代码
export default function GetWeather(props) { const [weather, setWeather] = useState({}); // 初始值改为对象更匹配存储结构 const apiKey = "xxxxx"; const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid=${apiKey}`; useEffect(() => { console.log("In useeffect"); // 在异步回调中处理数据并更新state fetch(apiUrl) .then((res) => res.json()) .then((data) => { setWeather({ data: data }); // 直接打印接口返回的data,确保拿到有效数据 console.log("接口返回数据:", data); }) .catch((err) => { // 捕获请求异常,方便排查问题 console.error("请求失败:", err); }); }, [apiUrl]); // 若要查看更新后的state,可在组件顶层打印,每次渲染都会输出最新值 console.log("更新后的weather状态:", weather); return <div>{/* 此处添加组件渲染内容 */}</div>; }
关键修正点
- 把
useState初始值从数组[]改为对象{},匹配后续存储的{data: ...}结构。 - 将
setWeather和数据日志放在fetch的第二个.then回调内,确保拿到解析后的真实接口数据。 - 添加
catch捕获请求错误,避免请求失败时无提示。 - 若需查看更新后的state,要么在回调里打印接口返回的
data,要么在组件顶层打印(能获取到最新的state值)。
内容的提问来源于stack exchange,提问作者Geethika
相关产品推荐
相关产品推荐

