【发布时间】:2020-09-18 10:52:11
【问题描述】:
我刚刚开始学习 React,并且正在尝试使用 PokeAPI 构建 PokeDex,但我很难理解如何从 API 中获取数据。我想获取前 384 个 Pokemon 相关信息。我在下面的 componentDidMount() 中编写了这段代码,以提取我的主 App 类组件中的完整数据,并将其推送到一个名为 pokemonArray 的数组中,我将设置为我的状态。
let pokemonArray = [];
/* First API fetch call to return names and URL's of first 384 Pokemon after promise is resolved.*/
fetch('https://pokeapi.co/api/v2/pokemon/?limit=384')
.then(response => response.json())
.then(data => {
let results = data.results;
let promisesArray = results.map(result => {
return fetch(result.url).then(response => response.json()).then(data => pokemonArray.push(data));
})
return Promise.all(promisesArray)
}).then(this.setState({ pokemon: pokemonArray }, () => console.log('Main Pokemon State: ', this.state.pokemon)));
}
在我的渲染方法中,我想将这个新设置的状态作为道具传递给一个名为 PokeList 的组件,就像这样
<PokeList pokemon={this.state.pokemon} />
一旦我传递它并尝试像这样在我的 PokeList 组件中呈现它
export const PokeList = ({ pokemon }) => {
console.log(pokemon);
return (
<div className="pokecard-container">
<h1>{pokemon[0].id}</h1>
</div>
);
}
我收到一条错误消息,提示 TypeError: Cannot read property '0' of null。 React Developer 工具显示了使用检索到的值填充的状态以及正在设置的道具,但它似乎认为它为空。谁能帮忙解决这个问题,看到这个错误真是令人沮丧
【问题讨论】:
-
你的应用没有
pokemon数组;它必须等待获取,因此您需要在 pokemon 加载之前为 pokemon 和初始行为提供初始值 -
谢谢,有一个条件有助于防止它再次出错
标签: javascript html css reactjs frontend