【问题标题】:React: JS TypeError: items.map is not a function反应:JS TypeError:items.map 不是函数
【发布时间】:2020-10-12 05:49:03
【问题描述】:

我正在尝试使用 react 显示来自 API 的项目列表。

在我的组件类 Explore 中,我想编写从 api 获取和显示数据的代码。

itemsthis.stateitems.stateitems.state.results 上使用 .map 时(在我的查询中需要的数据上)我收到以下错误:

Cannot read property 'map' of undefined** || **TypeError: this.state.map is not a function

Unhandled Rejection (TypeError): items.map is not a function

是组件本身结构的问题吗?使用渲染或物品声明? 我错过了thisthis.state 的内容吗?是否需要在.map中添加功能(或更改密钥)?

当我控制台日志(在代码的渲染部分)itemsitems.results 时,我确实在地图调用之前获得了我需要的数据。

感谢您的帮助。

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

class Explore extends Component {
    constructor(props){
      super(props);
  
      this.state = {      
        items: [],
      };
    }
      componentDidMount(){
  
          fetch('https://myapi/search/photos?query=myquery&client_id=myclientid')
          .then(res => res.json())  
          .then(json => {
              this.setState({
                isLoaded: true,
                items: json,  
              });           
          });
        }
      
        
   render() {
        var { items } = this.state;
    return (
      <div>
        <h1>Nav to</h1>
        <div>           
            <ul> 
                {items.map(item => (
                    <li key={item.results.id}>
                        <a href={ItemDetail}>Alt: {item.results.altdescription} | </a>
                            Desc:{item.results.desc}
                    </li>))}
            </ul>
        </div>
    </div>       

    );
    }     
}

export default Explore;

【问题讨论】:

  • json 是一个数组吗?
  • 你确定在这个``` .then(json => { this.setState({ isLoaded: true, items: json, }); });``` json 是一个数组吗?
  • 嗨,如上所述,您的“项目”根本不是数组,因此 .map 将不可用。

标签: javascript reactjs react-native typeerror array.prototype.map


【解决方案1】:

在调用 .map 之前,尝试添加检查项是否已设置以及是否为数组。

在你调用map的那一行添加items &amp;&amp; !!items.length &amp;&amp; items.map...

此外,问题可能出在您接收数据的格式上。 在调用this.setState之前尝试console.logjson

【讨论】:

  • 如果我在调用 setState 之前控制台记录 json 中收到的数据:{total: 85169, total_pages: 8517, results: Array(10)} 作为包含我需要的结果数组的对象接收的数据?
  • 尝试将 `this.setState({ isLoaded: true, items: json, });` 更改为 `this.setState({ isLoaded: true, items: json.results, });`
  • this.setState({ isLoaded: true, items: json.results, });成功了!谢谢
猜你喜欢
  • 1970-01-01
  • 2021-03-17
  • 2023-02-17
  • 2019-07-31
  • 2021-01-04
  • 2017-01-28
  • 2019-08-03
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多