【问题标题】:Getting JSON info from API从 API 获取 JSON 信息
【发布时间】:2020-09-03 02:16:00
【问题描述】:

我正在使用 Axios(Apisauce) 将 API 连接到 React Native App; 这是我尝试使用 FlatList 在应用内显示的 JSON 文件:

{
  "data": {
    "sideMenu": {
      "url": "https://google.com",
      "icons": [
        {
          "id": 1,
          "url": "https://google.com",
          "status": 1
        },
      ]
    },
  }
}

当我尝试将其登录到控制台时,使用 console.log(response.data) 会返回所有 API 信息,但使用 console.log(response.data.data) 不会返回我正在寻找的对象!

我尝试过JSON.stringify()toString(),但它们似乎都不起作用。

我的 Axios 代码:

const getServices = () => {
  const service = "https://api.team-grp.ir/app/json/services2.json/";

  return client.get(service);
};

我的源代码:

  const ServiceInfo = async () => {
    await getServices()
      .then((response) => {
        if (response.ok) {
          setServicesData(response.data.data);
        }
      })
      .catch((error) => {
        console.warn(error);
        setServicesData([]);
      });
  };


useEffect(() => {
ServiceInfo();
});

【问题讨论】:

  • 你能分享你的 axios 代码吗?
  • 请附上您的源代码。
  • @DevLover 编辑的主要问题
  • @C.K 编辑主要问题

标签: react-native axios react-native-flatlist apisauce


【解决方案1】:

你不应该使用 async/await 和 .then/.cache ... 这段代码对我有用: (您还可以在此答案的底部看到我的示例代码图像,其中包含一个伪造的 getService 函数,您将看到记录的响应是正确的)

const ServiceInfo = () => {
    getServices().then((response) => {
        if (response.ok) {
          setServicesData(response.data.data);
        }
      })
      .catch((error) => {
        console.warn(error);
        setServicesData([]);
      });
  };


useEffect(() => {
   ServiceInfo();
}, []);

【讨论】:

  • 谢谢!我会检查的
【解决方案2】:
const ServiceInfo = async () => {
    await getServices()
      .then((response) => {
          return response.json();
      })
      .then((response) => {
         setServicesData(response.data);
       })
      .catch((error) => {
        console.warn(error);
        setServicesData([]);
      });
  };

试试这个

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-30
    • 2021-10-28
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2012-07-14
    • 2016-10-05
    相关资源
    最近更新 更多