未捕获的TypeError:this.state.pokemon.filter不是函数吗? [英] Uncaught TypeError: this.state.pokemon.filter is not a function?
问题描述
尝试获取pokeapi并映射从api返回的数据数组.我将状态设置为一个空数组,然后继续尝试获取api并从响应中接收数据,并将其添加到我的神奇宝贝状态
Trying to fetch the pokeapi and map through the array of data returned from the api. I set my state to an empty array and then I proceed to try and fetch the api and receive data from the response, and add it to my pokemon state
class App extends Component {
constructor() {
super()
this.state = {
pokemon: [],
searchfield: ''
}
}
componentDidMount() {
fetch('https://pokeapi.co/api/v2/pokemon/')
.then(response => response.json())
.then(pokemon => this.setState({ pokemon: pokemon }))
.catch(err => console.log(err));
}
onSearchChange = (e) => {
this.setState({ searchfield: e.target.value })
}
render() {
const filteredPokemon = this.state.pokemon.filter(poki => {
return
poki.name.toLowerCase().includes
(this.state.searchfield.toLowerCase());
})
if (!this.state.pokemon.length) {
return <h1>Loading</h1>
} else {
return (
<div className='tc'>
<h1>Pokemon</h1>
<SearchBox searchChange={this.onSearchChange}
/>
<Scroll>
<CardList pokemon={filteredPokemon} />
</Scroll>
</div>
);
}
}
推荐答案
此api调用会导致 this.state.pokemon
被设置为对象而不是数组:
This api call results in this.state.pokemon
being set to an object not an array:
fetch('https://pokeapi.co/api/v2/pokemon/')
.then(response => response.json())
.then(pokemon => this.setState({ pokemon: pokemon }))
.catch(err => console.log(err));
我相信您正在尝试过滤作为数组的 results
属性?在这种情况下,请将 this.state.pokemon
设置为 pokemon.results
:
I believe you are trying to filter on the results
property which is an array? In this case, set this.state.pokemon
to pokemon.results
:
fetch('https://pokeapi.co/api/v2/pokemon/')
.then(response => response.json())
.then(pokemon => this.setState({ pokemon: pokemon.results }))
.catch(err => console.log(err));
您可能已经调试了提取操作,以看到如下所示的对象:
You could have debugged the fetch to see the object like this:
fetch('https://pokeapi.co/api/v2/pokemon/')
.then(response => response.json())
.then(pokemon => console.log(pokemon))
.catch(err => console.log(err));
这篇关于未捕获的TypeError:this.state.pokemon.filter不是函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!