You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Axios GET请求返回的嵌套对象赋值给React Native Hook?

问题成因
  • 请求参数为空导致接口404:获取用户ID的getData是异步方法,setCurrentUsersID更新状态为异步操作,useFocusEffect触发getHistory时,currentUsersID还停留在初始空值,最终请求URL为http://localhost:5000/daysLog/getLog/,和后端路由不匹配触发404。
  • 初始状态无默认值导致渲染报错:historyData初始值为undefined,组件首次渲染时接口请求还未返回,直接访问historyData[0].totalCalories相当于读取undefined的属性,触发类型错误。
  • iOS端请求地址无效:iOS模拟器/真机无法直接识别localhost指向开发机本地服务,也会触发接口404错误。
  • 副作用依赖缺失:useCallback未添加依赖项,会导致重复触发无效请求,同时getData直接在组件顶层调用,每次组件渲染都会重复执行。
解决方案
  1. 调整请求触发逻辑
    把getData放到useEffect中执行,同时监听currentUsersID,只有当用户ID存在时才发起数据请求:
// 组件内替换原getData调用逻辑
React.useEffect(() => {
  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem("@storage_Key");
      if (value !== null) {
        setCurrentUsersID(value);
      }
    } catch (error) {
      console.log("Error reading AsyncStorage value -> " + error);
    }
  };
  getData();
}, []);

// 监听currentUsersID触发请求
useFocusEffect(
  React.useCallback(() => {
    if (currentUsersID) {
      getHistory();
    }
  }, [currentUsersID])
);
  1. 给状态添加默认值 + 渲染安全判断
// 初始值设为空数组
const [historyData, setHistoryData] = React.useState([]);

// 渲染时用可选链或者条件判断避免报错
<Text style={{ color: "white" }}>
  History: {historyData[0]?.totalCalories ?? '无数据'}
</Text>
  1. 修正iOS端请求地址
    把请求URL中的localhost替换为开发机的局域网IP,例如:
const response = await axios.get("http://192.168.1.102:5000/daysLog/getLog/" + currentUsersID);

内容的提问来源于stack exchange,提问作者xv8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:45:05