【问题标题】:Keep getting TypeError: .map is not a function不断收到 TypeError:.map 不是函数
【发布时间】:2021-03-21 00:56:37
【问题描述】:

我正在使用 Pokemon API 制作一个 react.js 应用程序来扩展我对 React 的理解。我在尝试映射状态 pokeList 时遇到了问题。每次我渲染页面时,它都会显示TypeError: pokeList.map is not a function。几个小时以来,我一直在尝试几种不同的东西,但在 Google 上找不到任何有用的东西。

代码底部的注释是我尝试的另一种方法,它返回相同的错误。

import React, { useEffect, useState } from 'react';
import axios from 'axios';

import Card from '../components/CardView';
import Selected from '../components/Selected';

const Main = (props) => {

  const [pokeList, setPokeList] = useState([]);
  const [selectedPokemon, setSelectedPokemon] = useState("");
  const [selectedPokeData, setSelectedPokeData] = useState([]);
  const [loaded, setLoaded] = useState(false);
  let renderNum = 10;

  useEffect(() => {
    axios.get("https://pokeapi.co/api/v2/pokemon?limit=" + renderNum)
      .then(res => setPokeList(res.data))
  }, [])

  useEffect(() => {
    axios.get("https://pokeapi.co/api/v2/pokemon/" + selectedPokemon)
      .then(res => setSelectedPokeData(res.data))
      .then(setLoaded(true))
  }, [])

  return(
    <div className="container">
      {loaded === false ?

      <h1>loading...</h1> :

      <div className="row">
        <div className="col">
          {pokeList.map((pokemon, idx) =>
            <div key={idx}>
              <Card pokeData={pokemon} selectedPokemon={selectedPokemon} />
            </div>
          )}
        </div>
        <div className="col">
          <Selected pokeData={selectedPokeData}/>
        </div>
      </div>
      }
    </div>
  )
}

export default Main;

// {pokeList.map(pokemon => {
//   return (
//       <div>
//         <Card allPokeData={pokemon} currentSelectedPokemon={selectedPokemon}/>
//       </div>
//     )
//   })}

我的目标是通过道具发送来自每个单独口袋妖怪的数据,并渲染每个口袋妖怪的名称、类型和图片。因此,当页面第一次呈现时,应该会显示 10 个 pokemon 及其信息。

【问题讨论】:

  • res.data 可能不是数组

标签: javascript reactjs


【解决方案1】:

这样做的原因是因为您从 Pokemon API 错误地分配了返回值。您尝试分配的 arrayres.data.results 内。

所以改为:

useEffect(() => {
  axios.get("https://pokeapi.co/api/v2/pokemon?limit=" + renderNum)
    .then(res => setPokeList(res.data.results))
}, []);

无论如何,确保分配给变量的类型始终是一种好习惯,特别是当它是您要映射的数组时。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 2020-08-02
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多