React: JS TypeError: items.map 不是一个函数



我正在尝试显示来自 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;

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

在你调用地图的行上添加items && !!items.length && items.map...

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

最新更新