首页 > 解决方案 > 我不明白错误: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>
        )
    }
}

我对自己做错了什么感到有些困惑,有什么想法吗?

标签: javascriptreactjs

解决方案


这是我使用 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 遍历您拥有的所有事件并显示这些事件。

我希望这有帮助。祝你好运!


推荐阅读