【问题标题】:data.json is not a function reactjs using Fetch APIdata.json 不是使用 Fetch API 的函数 reactjs
【发布时间】:2019-11-02 15:23:00
【问题描述】:

我有使用 fetch api 的删除功能,但是在删除时,我收到了这个错误,data.json is not a function

这是我的代码

export const deleteLeaveType = async id => {
  const response = await fetch(
   `${API_LINK}/route/route/route/${id}`, {
    method: 'delete',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${Auth.getToken()}`,
     },
   }
  );
  return getData(response);
};

我在另一个文件中调用它

const deleteLeaveType = async id => {
  let deleteLeaveType = isLeaveType.filter(
    item => item.id !== id
  );

  await CalendarManagementAPI.deleteLeaveType(id)
    .then(data => {
      console.log(data.json());
      setLeaveType(deleteLeaveType);
    });
    setLoadingLeaveTypes(false);
    fetchLeaveTypes();
  })
  .catch(error => {
    console.log(error);
  });
};

【问题讨论】:

  • 什么是getData?此外,如果您使用的是await,则不需要使用.then;就做const data = await CalendarManagementAPI.deleteLeaveType(id)
  • 这是承诺响应。
  • @AlyssaReyes 你看下面的答案了吗?

标签: javascript reactjs fetch-api


【解决方案1】:

主要问题:

您遇到的主要问题是,在您的顶级 deleteLeaveType 函数中,您以 return getData(response) 结尾,而不是仅返回您从 fetch 请求中收到的任何内容。

正如您从the docs 中看到的那样,使用fetch 的正常方法是只执行const response = await fetch(...)(就像您已经完成的那样),然后在调用data.json() 之后立即执行(这是另一个异步函数,顺便一提)。但是,您的 getData(response) 函数可能不会完全返回您期望的结果。

其他cmets:

正如 cmets 中所述,您可能不应该同时使用 async / await.then()。这是处理异步函数的两种不同方式,因此一次只能使用一种。

在您的deleteLeaveType 函数中,如果您更喜欢使用.then 来处理异步函数,您可以像这样摆脱或asyncawait

// remove 'async' from function declaration
const deleteLeaveType = id => {
  // keep original code      

  // remove 'await'
  CalendarManagementAPI.deleteLeaveType(id)
    .then(data => {
      // ... everything else the same
};

以正确的方式使用async / await,就像您在问题的第一个deleteLeaveType 中使用的那样,这样做:

const deleteLeaveType = async id => {
  let deleteLeaveType = isLeaveType.filter(
    item => item.id !== id
  );

  let data = await CalendarManagementAPI.deleteLeaveType(id);

  // ... the rest of your code
};

这是一篇有趣的文章,解释了使用 async / await 处理错误的一些想法,如果您有兴趣:Better error handling with async / await

我还建议不要将相同的变量名deleteLeaveType 用于两个函数一个数组。这可能会让您在任何给定时刻所引用的内容有些混乱。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 2016-12-09
    • 1970-01-01
    • 2020-02-29
    • 2018-11-30
    • 2023-01-23
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多