繁体   English   中英

反应:JS TypeError:items.map 不是 function

[英]React: JS TypeError: items.map is not a function

我正在尝试显示来自 API 的项目列表并做出反应。

在我的组件 class Explore中,我想对来自 api 的获取和显示数据进行编码。

While using .map on items , this.state , items.state or items.state.results (on the data I need from my query) I'm getting the following errors:

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的某些内容? 我是否需要将 function 添加到.map (或更改密钥)?

当我控制台日志(在代码的渲染部分) items或项目.结果时,我确实在items.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;

在调用.map 之前,尝试添加一个检查以查看是否设置了项目以及它是否是一个数组。

在您调用 map 的行上添加items &&..items.length && items.map...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM