首页 > 解决方案 > 获取 VANILLA JS 时无法读取未定义的属性“地图”

问题描述

当我在控制台中一个接一个地启动splitArray(people, 5)displayContent(0)运行时,它们工作得很好,但是当我将它们添加.then()到我的 fetch 方法中时,我得到一个Uncaught TypeError: Cannot read property 'map' of undefined错误。

我正在尝试制作我的第一个应用程序,它将 JSON 文件显示为带有分页、排序方法等的表格。我在这里搜索了答案,但我发现的每个线程似乎都是关于 REACT 的。我正在尝试使用纯香草 js 来做到这一点。

const endpoint = 'https://api.myjson.com/bins/agowj';
let people = [];
let peeps = [];
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => people.push(...data))
  .then(splitArray(people, 5))
  .then(displayContent(0));

function displayContent(page) {
  let suggestions = document.querySelector('.suggestions');
  let html = peeps[page].map(person => {
    return `
    <tr>
    <td>${person.id}</td>
    <td>${person.firstName}</td>
    <td>${person.lastName}</td>
    <td>${person.dateOfBirth}</td>
    <td>${person.function}</td>
    <td>${person.experience}</td>
    </tr>
    `}).join("");
    suggestions.innerHTML = html;
  };

  function splitArray(arr, size) {
  peeps = [];
  for (i=0; i < arr.length; i += size){
    peeps.push(arr.slice(i, i + size));
  }
  return peeps;
}

我怎样才能使这项工作?

标签: javascriptdictionary

解决方案


您将这些方法的结果传递给then. 您需要传递一个函数:

.then(() => splitArray(people, 5))
.then(() => displayContent(0));

推荐阅读