javascript - 我不明白错误:this.state.categories.map is not a function ReactJS
问题描述
我对 React JS 还很陌生,我遇到了无法在我正在使用的状态数组上使用 map 函数的错误。
我目前正在使用 Eventbrite api 构建一个 webapp,从 api 获取数据不是问题。但是当我想遍历给定的数据时,React 会响应我上面给出的错误。
import React, { Component } from 'react'
import axios from 'axios'
export default class Categories extends Component {
state={
apiUrl : 'https://www.eventbriteapi.com/v3/categories/103',
OAuthToken : 'my OAuthToken',
loading: true,
categories: []
}
componentWillMount(){
axios.get(`${this.state.apiUrl}?token=${this.state.OAuthToken}`)
.then(res => {
let result = res.data;
this.setState({categories : result});
console.log(this.state.categories);
if(this.state.result !== ''){
this.setState({loading:false});
}
})
.catch((error)=>{
console.log(error);
})
}
renderCategories(){
if(this.state.loading === false){
return(
<ul>
{this.state.categories.map(item=> (
<li key={item}>{item}</li>
))}
</ul>
)
}
}
render() {
return (
<div>
{this.renderCategories()}
</div>
)
}
}
我对自己做错了什么感到有些困惑,有什么想法吗?
解决方案
这是我使用 fetch() 执行此操作的方法...
fetch('https://www.eventbriteapi.com/v3/organizers/{organizer_id}/events/?status=live&token=******')
.then(response => response.json())
.then(data => gatherData(data.events))
function gatherData(data) {
const options = data.map(item => `
<div id="event-contain">
<div class="event-left" style="width: 66%;">
<img src="${item.logo.url}">
<a href="${item.url}"><h5>${item.name.html}</h5></a><br/>
<p>${item.description.text}</p>
<a href="${item.url}"><button style="margin-bottom: 10px; padding: 15px;">Buy Tickets</button></a><br/><br/>
<div class="spacer" style="width: 100%; height: 30px; border-top: 1px solid #e4e4e4;"></div>
</div>
</div>
`).join('');
evdis.innerHTML = options;
}
您似乎缺少为 JSON 响应设置变量的步骤。然后,您应该能够进入 JSON 响应的最高状态(也称为 events),这将允许您使用 .map 遍历您拥有的所有事件并显示这些事件。
我希望这有帮助。祝你好运!
推荐阅读
- xml - Poppler/pdftohtml 和 ImageMagick/convert 的坐标系不同
- arrays - MongoDB:复杂数组字段
- postgresql - Web 应用程序 [ROOT] 似乎已经启动了一个名为 [pollingConfigurationSource] 的线程,但未能停止它。内存泄漏
- svg - SVG 样式
- javascript - 正则表达式接受 00.00 格式的数字
- sql - SQL SERVER 将 UTC DATETIME 转换为本地日期时间
- mysql - 根据其他 2 列的值更新列
- java - Mongo DB 写:哪个是多个 upsert 的更好方法?
- docker - 在 windows 10 上安装 Kafka docker 镜像(在 Windows Container 模式下)
- python - Python代码在我用setuptools打包并用pip安装后看不到数据文件