React从Flask获取数据:设置State后数组为空的问题排查
问题原因
React 中 useState 提供的状态更新函数是异步操作,调用 setProfileData(res) 后,React 会将状态更新加入任务队列,不会立刻修改 profileData 的值。所以你紧接着执行 console.log(profileData) 时,拿到的还是更新前的空数组旧值,并非状态没有被正确设置。
解决方案
只要接口返回的 res 是正确的对象数组,setProfileData(res) 已经完成了状态存入操作,只是无法通过立即打印的方式验证。你可以通过以下两种方式确认或使用最新状态:
方式一:用
useEffect监听状态变化
通过useEffect钩子监听profileData的变化,状态更新完成后会自动触发钩子内的代码,此时就能获取到最新值:const [profileData, setProfileData] = useState([]) // 监听profileData变化,状态更新后执行 useEffect(() => { console.log(profileData); }, [profileData]); function getData() { axios.get("http://192.168.29.72:5002/profile") .then((response) => { const res = response.data setProfileData(res) }).catch((error) => { if (error.response) { console.log(error.response) console.log(error.response.status) console.log(error.response.headers) } }) }方式二:直接打印接口返回的
res
既然已经确认res是正确的对象数组,直接打印res即可验证数据内容,setProfileData(res)已经将该值传递给状态更新逻辑,组件重新渲染时profileData就会是最新的数组:function getData() { axios.get("http://192.168.29.72:5002/profile") .then((response) => { const res = response.data setProfileData(res) console.log(res); // 直接打印接口返回的有效数据 }).catch((error) => { if (error.response) { console.log(error.response) console.log(error.response.status) console.log(error.response.headers) } }) }
你也可以在组件的 JSX 中直接使用 profileData(比如通过 map 渲染列表),就能看到状态更新后的内容。
内容的提问来源于stack exchange,提问作者sankar
相关产品推荐
相关产品推荐

