React函数组件axios请求先返回两次undefined后返回200原因问询
现象原因解释
该输出规律完全符合React函数式组件的渲染逻辑,两次undefined分别对应前两次组件渲染的执行结果:
- 第一次渲染:组件首次挂载时,
useState()未传入初始值,userWallet默认值为undefined,直接执行组件顶层的console.log(userWallet),输出第一个undefined。此时你存入Context的uid初始值通常为null,useEffect内的uid !== null判断不成立,不会发起axios请求。 - 第二次渲染:当App中Context的用户ID完成赋值,
uid变更触发组件重渲染。此时useEffect检测到uid变化才会发起axios请求,但axios是异步网络请求,发起请求后不会等待返回就会执行本次渲染的console.log(userWallet),此时userWallet还未被赋值,输出第二个undefined。 - 第三次渲染:axios请求成功后调用
setUserWallet更新状态,触发组件第三次渲染,此时userWallet已经拿到接口返回结果,输出正常响应值。
优化建议
- 给状态指定明确初始值,避免隐式undefined,方便后续做加载判断:
const [userWallet, setUserWallet] = useState(null)
- 新增加载、错误状态处理,避免页面渲染时报空值错误:
import { UidContext } from "../components/AppContext" import React, { useContext, useEffect, useState } from "react" import axios from "axios" export default function Balance() { const uid = useContext(UidContext) const [userWallet, setUserWallet] = useState(null) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) useEffect(() => { if (uid !== null) { setLoading(true) axios.get(`${process.env.REACT_APP_API_URL}api/balance/${uid}`) .then((res) => { setUserWallet(res.data[0]) setError(null) }) .catch(err => { setError(err) setUserWallet(null) }) .finally(() => { setLoading(false) }) } }, [uid]); if (loading) return <section>加载中...</section> if (error) return <section>请求失败,请稍后重试</section> return ( <section> {userWallet ? `钱包余额:${userWallet.balance}` : "暂无钱包数据"} </section> ) }
附请求返回结果截图

内容的提问来源于stack exchange,提问作者user14265379
相关产品推荐
相关产品推荐

