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

标签 javascript reactjs error-handling typeerror

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

TypeError: items.map is not a function.

我对 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;

最佳答案

items state 中的数组最初是一个空数组,更改 items 时会出现此错误到不是数组的东西。

查看您问题中 API 的响应,解析后您将从 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>);

    // ...
  }
}

关于javascript - 使用 React 和 API 时如何修复 "TypeError: items.map is not a function"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081822/

相关文章:

javascript - 使用多个变量打开不同的链接

reactjs - 调整大小后获取实际图像大小 React Native

javascript - 将条件样式应用于 React 中的组件 - 内联 CSS

error-handling - 尝试/除了不捕捉 future 的 TimeoutError

php - 使用PHP中的try catch block 进行错误处理

javascript - 替换 JavaScript 中的正则表达式匹配

javascript - Materialise 中的导航栏上没有侧边菜单按钮。

javascript - 用于 JQuery 登录的 HTML 表单或 div?

javascript - 模块构建失败: SyntaxError: Unexpected token error when trying to render a second component

node.js - 如何处理内部服务器 API 和 HTTP API 之间的错误