React:无法通过API获取数据



我是新来的。我试图通过apir获取数据,但我无法获得任何数据。而且,我也没有得到任何错误信息。这是我的代码。我试图添加if语句来检查是否获取数据。当我检查控制台时,我得到了错误信息。我哪里错了?谢谢你的宝贵时间。

import React, {Component} from "react";
class PokemonList extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: [],
};
}
componentDidMount() {
fetch('https://pokeapi.co/api/v2/pokemon?limit=20')
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error,isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {

return (

<ul>
{items ? items.map(item => (
<li>
<p key={item.id}>{item.name}</p>;
</li>
)) :
console.log('no data')}
</ul>
);
}
}

}导出默认PokemonList;

您试图获得的poksammon项目具有results密钥,而不是items。所以把result.items换成result.results,看看会发生什么。

最新更新