javascript - this.state.events.map 不是函数

标签 javascript reactjs api

我正在尝试从 API 中读取 json。我正在尝试映射事件变量并将其显示在带有 API json 字段标题的 h1 标记中,但我从控制台收到以下错误“his.state.events.map 不是函数” 如果有人知道发生了什么那就太好了,我一直在检查互联网上的各种资源,但没有一个有效 提前致谢!!!

这是我从控制台返回的响应中的一些 json 信息

{…}
​count: 8
​next: null
​overflow: false
​previous: null
​results: Array(8) [ {…}, {…}, {…}, … ]
import React, { Component } from "react";

class Home extends Component {
  constructor() {
    super();

    this.state = {
      isLoading: true,
      events: []
    };
  }

  componentDidMount() {
    this.fetchApi();
  }

  fetchApi() {
    fetch(
      "https://api.predicthq.com/v1/events/?q=sports&city=galway&country=IE",
      {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          Authorization: "Bearer 000000000000000000000000000000" // <---it's not this
        }
      }
    )
      .then(response => response.json())
      .then(response => console.log(response)); // <---when i add in this line
    // .then(response => this.setState({ 'events': response })) // <----and take out this one
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.events.map(function(event, index) { // <-----error here
            return <h1>{event.title}</h1>;
          })}
        </ul>
      </div>
    );
  }
}

export default Home;

最佳答案

访问response.results得到一个Array,然后就可以使用map操作符了:

.then(response => this.setState({ 'events': response.results }))

关于javascript - this.state.events.map 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59080779/

相关文章:

javascript - react 子组件更新父组件时出现反模式错误

javascript - YouTube API播放来自标签的随机视频

javascript - Ruby Hpricot RegEx 替换 <BR >'s with <P>' s

reactjs - Material-ui:扩展面板和折叠面板的区别

javascript - AngularJS 是否在 $error.maxlength 对象中存储了一个值?

node.js - Webpack 生产 process.env.PORT=在服务器编译时未定义(React 应用程序)

javascript - 当我在我的文本框中输入故事时,它应该点击这个 api

c# - HttpClient 不接受授权 header (401 未授权)?

javascript - 语义 UI - 使用动态输入自动完成搜索

javascript - 我的 javascript 书签什么也没做,我哪里搞砸了?