【问题标题】:React native: Axios Get accusing Network ErrorReact Native:Axios Get 指责网络错误
【发布时间】:2020-09-28 13:19:46
【问题描述】:

我正在使用 Axios 编写我的第一个 react-native 程序,但在调用 get 时发现了问题。假设这是网络错误,我认为问题出在下面。

Api.js:

import axios from "axios";

const api = axios.create({
  baseURL: "https://192.168.15.8:3333",
});

export default api;

index.js

 async function loadIncidents() {
    if (loading) {
        return;
    }

    if (total > 0 && incidents.length === total) {
        return;
    }

    setLoading(true);
    try {
        const response = await api.get("/incidents", {
            params: { page },
        });

        setIncidents([...incidents, ...response.data]);
        setTotal(response.headers["x-total-count"]);
        setPage(page + 1);
    } catch (err) {
        console.log('Ocorreu um erro: ', err)
    }
    setLoading(false);
}

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

【问题讨论】:

  • 您正在使用 await 但未处理响应。检查 Mozilla 文档上的 asnyc await

标签: javascript react-native networking axios


【解决方案1】:

你可以使用try() catch()

async function loadIncidents() {
    if (loading) {
      return;
    }

    if (total > 0 && incidents.length === total) {
      return;
    }

    setLoading(true);

    let response;
    try {
     response = await api.get("incidents", {
      params: { page },
    });
    } catch (ex) {
       console.log(ex);
    }
    setIncidents([...incidents, ...response.data]);
    setTotal(response.headers["x-total-count"]);
    setPage(page + 1);
    setLoading(false);
  }

【讨论】:

    猜你喜欢
    • 2022-06-18
    • 2018-01-09
    • 1970-01-01
    • 2021-11-21
    • 2020-08-25
    • 1970-01-01
    • 2020-10-11
    • 2017-11-20
    • 2021-04-18
    相关资源
    最近更新 更多