【问题标题】:How to fix "TypeError: items.map is not a function" when working with React and APIs?使用 React 和 API 时如何修复“TypeError:items.map 不是函数”?
【发布时间】:2019-07-31 14:01:40
【问题描述】:

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

TypeError: 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;

【问题讨论】:

    标签: javascript reactjs error-handling typeerror


    【解决方案1】:

    由于状态中的items 数组最初是一个空数组,因此当您将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>);
    
        // ...
      }
    }
    

    【讨论】:

      【解决方案2】:

      由于您没有为任何内容指定类型,而且还不清楚(即使对于人类读者而言)itemsArray,您应该明确告诉 TypeScript 将其用作数组。

      您为此目的使用Type Assertion。应该是这样的:

      (items as Array<YourArrayElementType>).map(/* .. */);
      

      但是,作为一种好的做法,您应该始终明确指定您声明的任何内容的类型。这样,您代码库中的任何内容都将被静态类型化。对于来自外部的任何内容(例如 API 请求),您应该将信息转换为您定义的 interfaces

      【讨论】:

        【解决方案3】:

        就您的具体问题而言,Tholle 是绝对正确的……我会像这样进一步清理您的代码:

        import React, { Component } from 'react';
        
        class App extends Component {
          state = { items: [], isLoading: true, error: null };
        
          componentDidMount() {
            fetch('http://www.colr.org/json/colors/random/7')
              .then(res => res.json())
              .then(json => {
                this.setState({
                  isLoading: false,
                  items: json.colors,
                });
              })
              .catch(error =>
                this.setState({ error: error.message, isLoading: false }),
              );
          }
        
          renderColors = () => {
            const { items, isLoading, error } = this.state;
        
            if (error) {
              return <div>{error}</div>;
            }
        
            if (isLoading) {
              return <div>Loading...</div>;
            }
        
            return (
              <div>
                {items.map(item => (
                  <div key={item.id}>Hex: {item.hex}</div>
                ))}
              </div>
            );
          };
        
          render() {
            return <div>{this.renderColors()}</div>;
          }
        }
        
        export default App;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-12
          • 1970-01-01
          • 2020-08-07
          • 2020-02-09
          • 1970-01-01
          • 2019-09-21
          • 1970-01-01
          • 2021-12-01
          相关资源
          最近更新 更多