【发布时间】:2019-04-28 01:53:21
【问题描述】:
我是 React 新手,正在学习使用 Poke API (https://pokeapi.co) 的教程。
我正在使用 whatwg-fetch 向 API 发出请求。这会将 API 中的数据作为对象保存到“selectedPokemon”状态。
this.state = {
// other states
showModal: false,
selectedPokemon: null
};
我想将该数据发送到一个组件(在我的例子中是一个模态),所以我更新了我的模态组件调用,以将 selectedPokemon 状态作为道具包含在内:
<PokemonModal pokemon={this.state.selectedPokemon} closeModal={this.handleModalClose} showModal={this.state.showModal} />
我还更新了我的 PokemonModal 组件(在 PokemonModal.js 上)以包含 pokemon 作为道具:
const PokemonModal = ({showModal, closeModal, pokemon}) => {
但是,当我在PokemonModal 中使用该道具时,例如:
<Modal.Title>{pokemon.name}</Modal.Title>
我收到一个错误
未捕获的类型错误:无法读取 null 的属性“名称”
(这与我尝试使用的对象的任何其他部分相同,例如 pokemon.order。showModal 和 closeModal 道具按预期工作。)
有谁知道我如何向另一个组件发送和使用 JSON 对象?
如果重要的话,我的 fetch 函数就是这样设置的。 console.log 返回预期结果,即来自:https://pokeapi.co/api/v2/pokemon/10125/
的对象 handleModalOpen(pokemon) {
if(pokemon.url !== undefined) {
fetch(`${pokemon.url}`)
.then(response => {
return response.json();
})
.then(json => {
this.setState({
selectedPokemon: json,
showModal: true
})
console.log('selected: ' + this.state.selectedPokemon);
})
.catch(ex => {
console.log('pasrsing failed ' + ex);
})
}
}
【问题讨论】:
标签: javascript json reactjs javascript-objects