我试图去的special_abilities
阵列在下面的API端点:http://www.dnd5eapi.co/api/monsters/1反应取返回不可用__proto__ obejcts
这里是我的容器组件:
import React, { Component } from 'react'
import { Link } from 'react-router';
import MonsterSpecialAbilities from '../components/MonsterSpecialAbilities'
class MonstersContainer extends Component {
constructor(props) {
super(props)
this.state = {
monster: {},
number: Math.floor((Math.random())*325)
}
this.handleRandomClick = this.handleRandomClick.bind(this)
}
componentDidMount() {
fetch(`http://www.dnd5eapi.co/api/monsters/${this.state.number}`)
.then(response => response.json())
.then(responseData => {
this.setState({ monster: responseData })
})
}
render() {
let spec_abilities;
spec_abilities = this.state.monster.special_abilities.map((ab) => {
return(
<MonsterSpecialAbilities
desc={ab.desc}
/>
)
})
return(
<div>
{this.state.monster.name}
{spec_abilities}
</div>
)
}
}
export default MonstersContainer
眼下.map
功能打破我的组件,我得到控制台错误:Uncaught TypeError: this.state.monster.special_abilities.map is not a function
。我试图访问this.state.monster.special_abilities[0]
访问数组,但这返回为null
,导致我相信它是一个无效的数组。
我试图创建一个州名monster_special_ability
并手动通过以下方法设置数组:
componentDidMount() {
fetch(`http://www.dnd5eapi.co/api/monsters/${this.state.number}`)
.then(response => response.json())
.then(responseData => {
this.setState({ monster: responseData })
this.setState({ monster_special_abilities: responseData.special_abilities })
})
}
我试图把调试器在setState
功能,并键入responseData.special_abilities
到控制台返回数组我想要的,但状态设置后,似乎阵列不可用(它变成原型:对象)
任何帮助,将不胜感激!我很乐意澄清其他事情。
使用异步数据时要小心,在尝试使用它之前检查它是否已经可用:'this.state.monster.special_abilities'可能没有在第一次渲染中定义,但是在您获取它之后,它是 – BravoZulu
@BravoZulu ,我确实通过放入if语句来检查状态是否为空。我在浏览器控制台中得到了相同的回复。 –
你的陈述是什么?在下面检查我的答案,它可能会帮助你 – BravoZulu