【问题标题】:When using Fetch API I get this error: Uncaught (in promise) TypeError: packages.map is not a function使用 Fetch API 时出现此错误: Uncaught (in promise) TypeError: packages.map is not a function
【发布时间】:2020-01-03 02:27:41
【问题描述】:

我正在使用 Fetch API 从 API 的端点获取一些数据。

我收到此错误:

Uncaught (in promise) TypeError: package.map is not a function

我做了一些研究,似乎发生错误是因为响应是对象而不是数组。

这是一个代码示例:

 const url = 'https://reqres.in/api/users?page=2';

 const fetchPromise = fetch(url);

 fetchPromise.then(response => {

   return response.json();

 }).then(people => {

   // checks response value type
   console.log(typeof people);

   const names = people.map(person => person.name).join('\n');
 });

你可以找到我的sample code here

【问题讨论】:

  • 你能检查一下你从那个网址的回复吗?
  • 正确,响应是一个对象而不是数组。目前还不清楚您期望地图会做什么。

标签: javascript arrays object promise fetch


【解决方案1】:

希望这是你想要做的事情,

var url = 'https://reqres.in/api/users?page=2';

 var fetchPromise = fetch(url);

 fetchPromise.then(response => {

   return response.json();

 }).then(people => {
     console.log("people" , people.data);
   // checks response value type
   console.log(typeof people);
//here in the response of the people , it was object , but the people.data is array and on which you can use .map() .
   const names = people.data.map(person => person.first_name + " " + person.last_name).join('\n');
   console.log("names ==.>" , names);
 });

【讨论】:

  • 效果很好!谢谢!你介意添加解释为什么它有效吗?像这样,每个寻找相同问题的人都会理解,我也是:)
  • 我会去的,别担心。我只是在等待系统对我的投票设置的 3 分钟限制;)
  • 非常感谢。 @ManuelAbascal 。在上面的答案中,您需要任何解释,然后您可以随时问我。
  • 是的,为什么我的解决方案不起作用?您可以编辑答案以展示解释吗?
  • 非常感谢您的纠正。 @ManuelAbascal 。以后会照顾它的。对不起。
【解决方案2】:

您的 API 端点 https://reqres.in/api/users?page=2 正在返回一个对象,您只能将 map 用于数组。我猜你想使用返回对象的数据字段,它是一个人员对象数组。

const url = 'https://reqres.in/api/users?page=2';

 const fetchPromise = fetch(url);

 fetchPromise.then(response => {

   return response.json();

 }).then(people => {

   // checks response value type
   console.log(typeof people);

   const names = people.data.map(person => person.first_name).join('\n');
 });

【讨论】:

  • 由于解释,这应该是公认的答案。
猜你喜欢
  • 2017-04-13
  • 2020-03-17
  • 2020-01-06
  • 2021-03-10
  • 2021-09-30
  • 2020-12-22
  • 2019-06-15
  • 2017-07-20
  • 1970-01-01
相关资源
最近更新 更多