React中用API返回数据设置state为undefined但API数据正常如何排查
React状态设置为undefined问题修复方案
错误原因
- Promise链未正确传递返回值:第一个
then仅执行了打印操作,没有显式return res,导致下一个then接收到的入参为undefined,执行setCurrentCityData时自然传入了undefined。 - React的
setState是异步批量更新操作:同一个渲染闭包内,状态更新后立刻打印,拿到的依旧是本次渲染的旧值,状态更新会触发组件重渲染,下次渲染时才能获取到最新的状态值。 then回调写法错误:.then(console.log(currentCityData))的写法会同步立即执行console.log,再将执行结果传入then,而非等待Promise请求完成后再执行打印,此时请求尚未返回,拿到的是初始状态值。
修复代码
推荐使用async/await写法,可读性更强:
const [currentCityData, setCurrentCityData] = useState({}); const fetchData = async (cityValue) => { try { const res = await axios.get('http://localhost:5000/get-weather', { params: { cityValue: cityValue } }) const targetData = res?.data?.data[0] console.log('接口返回数据:', targetData) setCurrentCityData(targetData) } catch (error) { console.log('请求出错:', error) } }; useEffect(() => { fetchData('toronto&country=canada'); }, []); // 监听状态变化验证更新结果 useEffect(() => { console.log('currentCityData更新后的值:', currentCityData) }, [currentCityData])
如果你要保留原Promise链写法,修改后代码如下:
const fetchData = (cityValue) => { axios.get('http://localhost:5000/get-weather', { params: { cityValue: cityValue } }) .then(res => { console.log(res?.data?.data[0]) return res // 新增返回响应对象,传递给下一个then }) .then((res) => setCurrentCityData(res?.data?.data[0])) .then(() => console.log('本次渲染拿到的仍是旧值:', currentCityData)) // 改成箭头函数延迟执行 .catch(error => console.log(error)) };
内容的提问来源于stack exchange,提问作者chingu
相关产品推荐
相关产品推荐

