尝试获取pokeapi并映射从api返回的数据数组。我将状态设置为空数组,然后继续尝试获取api并从响应中接收数据,并将其添加到我的神奇宝贝状态

 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被设置为对象而不是数组:

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

fetch('https://pokeapi.co/api/v2/pokemon/')
   .then(response => response.json())
   .then(pokemon => this.setState({ pokemon: pokemon.results }))
   .catch(err => console.log(err));


您可能已经调试了提取以查看如下对象:

fetch('https://pokeapi.co/api/v2/pokemon/')
   .then(response => response.json())
   .then(pokemon => console.log(pokemon))
   .catch(err => console.log(err));

10-05 21:05