React中使用axios获取的数据无法赋值给useState问题求助
问题原因
React 中的 setState(包括 useState 返回的更新函数)是异步批量执行的,你调用 setWeather(res.data) 之后,当前作用域里的 weather 变量还是本次渲染时捕获的旧值(也就是初始的空数组),所以紧跟着的 console.log 必然打印空数组,并不是赋值失败了。
验证状态更新成功的方案
- 方法1:在组件顶层作用域打印
weather,每次组件重新渲染都会执行该代码,状态更新触发重渲染后就能拿到最新值
示例代码:const App = () => { const [weather, setWeather] = useState([]); const [loading, setLoading] = useState(true); // 每次渲染都会打印当前weather值,更新后会输出新值 console.log('当前weather状态:', weather) // Side effects useEffect(() => { axios .get("https://weather-app-tst.herokuapp.com/api/weather") .then((res) => { setLoading(false); setWeather(res.data); }) .catch((error) => console.log(error)) }, []); } - 方法2:如果需要在状态更新完成后执行后续逻辑,可以新增 useEffect 监听
weather变化,将逻辑写在该副作用内:useEffect(() => { // weather更新后会触发这个副作用执行 console.log('weather更新完成,最新值:', weather) // 依赖weather的业务逻辑都可以写在这里 }, [weather]) - 方法3:如果是需要在页面渲染weather相关内容,直接调用变量即可,状态更新后视图会自动刷新,无需额外处理:
return ( <div> {loading ? <p>加载中...</p> : <p>当前温度:{weather.temperature}</p>} </div> )
内容的提问来源于stack exchange,提问作者L.A.
相关产品推荐
相关产品推荐

