Javascript Can';t使用map函数绑定JSON数据
例如,我下面有这个JSON,我需要获取Javascript Can';t使用map函数绑定JSON数据,javascript,reactjs,ecmascript-6,arrow-functions,Javascript,Reactjs,Ecmascript 6,Arrow Functions,例如,我下面有这个JSON,我需要获取类型的名称 { "adult": false, "backdrop_path": "/5qxePyMYDisLe8rJiBYX8HKEyv2.jpg", "budget": 178000000, "genres": [ { "id": 12, "name": "Adventure" }, { "id": 28, "name": "Action" }, {
类型的名称
{
"adult": false,
"backdrop_path": "/5qxePyMYDisLe8rJiBYX8HKEyv2.jpg",
"budget": 178000000,
"genres": [
{
"id": 12,
"name": "Adventure"
},
{
"id": 28,
"name": "Action"
},
{
"id": 53,
"name": "Thriller"
}
],
"homepage": null
}
但是当我使用map函数时,React返回一个错误:
TypeError:this.state.persons.map不是函数
类内容扩展了React.Component{
状态={
人员:[]
}
componentDidMount(){
get(Config.apirl+353081+Config.apiKey)
。然后(res=>{
const persons=资源数据;
这个.集合状态({persons});
})
}
render(){
返回(
预算:{this.state.persons.Budget}
类型:{this.state.persons.map(person=>{person.Genres.name} )}
);
}
}
我认为您的状态应该是对象文本{}
,而不是[]
。另外,res.data
返回一个{..}
,而不是[]
。如果它返回一个数组,那么this.state.persons.budget
应该抛出错误,但它不会。这证明,persons
状态不是数组
state = {
persons: {
genres: []
}
}
然后
<Typography gutterBottom={true}>
<b>Genres:</b>{" "}
{this.state.persons.genres.map(genre => <li key={genre.id}>{genre.name}</li>)}
</Typography>;
类型:{'}
{this.state.persons.genres.map(genre=>{genre.name} )}
;
您确定它应该是this.setState({persons:res.data})
而不仅仅是this.setState({persons:res})代码>?您可以console.log
在axios回调中记录res
,查看它是否包含您认为的数据。res.data
是数组吗?我不这么认为,根据你提到的例外情况。@Thole是的,res数据包含我需要的。what is contains。。你能做console.log和show吗?如果res.data
看起来像你第一个代码片段中的对象,它会给你错误,因为常规对象没有map
方法。this.state.persons.genres
最初将是未定义的,所以这个.state.persons.genres.map将给您一个错误。是的,这也是正确的。它工作正常,谢谢大家。所以我需要在persons
构造函数中“说”我需要从res
中获得什么数组?
<Typography gutterBottom={true}>
<b>Genres:</b>{" "}
{this.state.persons.genres.map(genre => <li key={genre.id}>{genre.name}</li>)}
</Typography>;