我正在尝试从 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/