尝试从https://api.rawg.io/api/games/portal-2获取数据并将其显示在页面上。是不是因为API给我提供了一个.map不会处理的对象?如果是这种情况,我可以做些什么来使其成为一个数组呢
import React, { Component } from 'react'
import axios from 'axios'
class List extends Component {
state = {
results: []
}
componentDidMount() {
const url = `${`https://api.rawg.io/api/games/portal-2`}`;
axios.get(url).then(response => response.data)
.then((data) => {
this.setState({ results: data })
console.log("Hello" + this.state.data)
})
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
});
}
render() {
return (
<div>
<h1>List of Games</h1>
{this.state.results.map((games) => (
<li>{games.results}</li>
))}
</div>
);
}
}
export default List错误消息
TypeError: this.state.results.map is not a function
32 |
33 | return (
34 | <div>
> 35 | <h1>List of Games</h1>
| ^ 36 | {this.state.results.map((games) => (
37 | <li>{games.results}</li>
38 | ))}如果任何人有任何想法,将不胜感激
发布于 2020-08-23 10:08:41
https://api.rawg.io/api/games/portal-2应用编程接口终结点未返回数组。
如果你想显示“游戏列表”,你可以使用https://api.rawg.io/api/games,它返回一个JSON,但是"results“键有一个游戏列表,我想这就是你想要的。
我建议使用浏览器扩展,例如,以便更好地从浏览器可视化应用编程接口响应的结构。

发布于 2020-08-23 10:09:12
不能将结果状态设置为object,来自API的响应是object,而不是数组,因此react将抛出此错误。再次尝试设置结果状态(data.genres,data.platform...以此类推)

https://stackoverflow.com/questions/63542616
复制相似问题