【发布时间】:2020-10-12 05:49:03
【问题描述】:
我正在尝试使用 react 显示来自 API 的项目列表。
在我的组件类 Explore 中,我想编写从 api 获取和显示数据的代码。
在 items、this.state、items.state 或 items.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
是组件本身结构的问题吗?使用渲染或物品声明?
我错过了this 或this.state 的内容吗?是否需要在.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;
【问题讨论】:
-
json是一个数组吗? -
你确定在这个``` .then(json => { this.setState({ isLoaded: true, items: json, }); });``` json 是一个数组吗?
-
嗨,如上所述,您的“项目”根本不是数组,因此 .map 将不可用。
标签: javascript reactjs react-native typeerror array.prototype.map