使用 React 和 API 时如何修复“TypeError: items.map is not a function”?

Joh*_*son 3 javascript error-handling typeerror reactjs

我是 React 的新手,正在尝试从 API 中获取一些信息,但是在使用 .map 函数将检索到的数据传递到数组中时不断收到此错误:

类型错误:items.map 不是函数。

我对 JavaScript 不太熟悉,所以我不完全理解这里发生了什么。我已经包含了我的代码:

import React, { Component } from "react";
import "./App.css";

class App extends Component {
  constructor() {
    super();
    this.state = {
      items: [],
      isLoaded: true
    };
  }

  componentDidMount() {
    fetch("http://www.colr.org/json/colors/random/7")
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          items: json
        });
      });
  }

  render() {
    var { items, isLoaded } = this.state;
    var itemInfo = items.map(item => (
      <div key={item.colors.id}>Hex:{item.colors.hex}</div>
    ));

    if (!isLoaded) {
      return <div>{itemInfo}</div>;
    } else {
      return <div className="App">{itemInfo}</div>;
    }
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 6

由于itemsstate 中的数组最初是一个空数组,因此当您更改items为不是数组的内容时会出现此错误。

查看您问题中 API 的响应,您将在解析 JSON 后从 JSON 中获取一个对象。你想在响应中使用的数组在colors属性下,这个数组中的每个元素都有idhex属性。

class App extends Component {
  // ...

  componentDidMount() {
    fetch("http://www.colr.org/json/colors/random/7")
      .then(res => res.json())
      .then(res => {
        this.setState({
          isLoaded: true,
          items: res.colors
        });
      });
  }

  render() {
    var { items, isLoaded } = this.state;
    var itemInfo = items.map(item => <div key={item.id}>Hex:{item.hex}</div>);

    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)