React中调用this.state.pokemon.filter时报错:filter不是函数
解决PokeAPI请求后
filter is not a function的错误 嘿,我来帮你搞定这个问题!你遇到的Uncaught TypeError: this.state.pokemon.filter is not a function错误,核心原因是PokeAPI返回的数据结构和你预想的不一样。
错误原因拆解
你初始把this.state.pokemon设为了空数组,但调用PokeAPI返回的响应并不是直接的数组,而是一个包含多个字段的对象,结构大概是这样的:
{ "count": 1281, "next": "https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20", "previous": null, "results": [ {"name": "bulbasaur", "url": "https://pokeapi.co/api/v2/pokemon/1/"}, {"name": "ivysaur", "url": "https://pokeapi.co/api/v2/pokemon/2/"} ] }
你之前的代码把整个返回对象直接赋值给了this.state.pokemon,导致它从数组变成了普通对象,而对象是没有filter方法的,自然就报错了。
修复方案
只需要在setState的时候,把响应对象里的results数组取出来赋值给pokemon状态就行,修改后的componentDidMount代码如下:
componentDidMount() { fetch('https://pokeapi.co/api/v2/pokemon/') .then(response => response.json()) .then(data => this.setState({ pokemon: data.results })) // 取data里的results数组 .catch(error => console.error('请求Pokemon数据出错:', error)) }
这样修改后,this.state.pokemon就会保持数组类型,之后调用filter方法就不会再报错啦。
内容的提问来源于stack exchange,提问作者user6139948
相关产品推荐
相关产品推荐

