【发布时间】:2021-11-30 09:23:30
【问题描述】:
我是 React 新手。我试图通过 APı 获取数据,但我无法获取任何数据。此外,我也没有收到任何错误消息。这是我的代码。我尝试添加 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;
【问题讨论】:
标签: reactjs ajax react-native api