【问题标题】:How to loop through fetch array and display results with Next.js如何使用 Next.js 循环获取数组并显示结果
【发布时间】:2020-09-26 01:41:39
【问题描述】:

我正在尝试遍历一个数组并获取这些结果以单独显示在我的网站上,但我不断收到以下错误消息:

TypeError:this.props.fetched.map 不是函数

不知道为什么我会收到错误消息。有什么想法吗?

这是我目前正在处理的代码:

import React from "react";
import "isomorphic-unfetch";

export default class HomePage extends React.Component {
  static async getInitialProps() {
    const todoIdList = [1, 2, 3, 4];
    for (const id of todoIdList) {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
      const todo = await response.json();
      return { fetched: todo.title };
    }
  }

  render() {
    return (
      <>
        <div>
          {this.props.fetched.map((datafetch, index) => (
            <p>{datafetch}</p>
          ))}
        </div>
      </>
    );
  }
}

【问题讨论】:

  • api 调用的响应是什么?

标签: reactjs next.js


【解决方案1】:

你在这里调用这个 url https://jsonplaceholder.typicode.com/todos/${id} 它将返回一个对象。

你正在像这样return { fetched: todo.title }; 设置你的状态,这意味着你获取的变量现在持有一个字符串值。

但是 javascript 的 map 函数只适用于数组。因此,您会收到此错误。

你可以试试这样的

    const todoIdList = [1, 2, 3, 4]; 
    const todoTitles = []
    for (const id of todoIdList) {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
      const todo = await response.json(); 
      todoTitles.push(todo.title)
      
    }
    return { fetched: todoTitles };
  }

【讨论】:

    【解决方案2】:

    您正在尝试使用 map 迭代对象。

    如果要使用地图,首先需要对其进行转换。然后,您可以尝试以下操作:

    {
        let aux = [];
        for (let [key, value] of Object.entries(this.props.fetched)) {
            aux.push(value);
        }
    
        aux.map((datafetch, index) => (
            <p>{datafetch}</p>
        ));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      相关资源
      最近更新 更多