当我在控制台分别记录变量“ pokemons”时,它确实返回一个数组。但是当我尝试映射它时,出现错误:TypeError:pokemons.map不是一个函数
我的代码:
import React, { useState, useEffect } from "react";
import "./App.css";
import PokeList from "./components/PokeList";
import Paginator from "./components/Paginator";
import axios from "axios";
function App() {
let [pokemons, setPokemons] = useState([]);
let [status, setStatus] = useState(false);
useEffect(
() =>
setPokemons(
axios.get("https://pokeapi.co/api/v2/pokemon").then((res) => {
setPokemons(res.data.results.map((poki) => poki.name));
})
),
[]
);
return (
<div className="App">
<PokeList pokemons={pokemons}></PokeList> <Paginator></Paginator>
</div>
);
}
export default App;
,然后在PokeList组件中调用该地图:
import React from "react";
const PokeList = ({ pokemons }) => {
console.log(pokemons.map((poki) => "Yellow"));
return (
<div>
<h1>Here are all your pokis: </h1>
</div>
);
};
export default PokeList;
答案 0 :(得分:1)
因为您将整个axios promise object
包装到setPokemans中:
尝试以下方法:
以下代码返回一个promise对象,而不是数组!
axios.get("https://pokeapi.co/api/v2/pokemon").then((res) => {
setPokemons(res.data.results.map((poki) => poki.name));
}) // returns object
答案 1 :(得分:1)
您的map()
失败的原因是axios返回了前几个电话的承诺。因此,您的子组件正在尝试映射一个诺言,这当然是无法做到的。解决此问题的另一种方法是检查数组的长度,并仅在有长度的情况下进行映射。
if(pokemons.length){
pokemons.map((poke) => {
console.log(poke)
})
}
以下是显示其正常工作的链接:https://codesandbox.io/s/tempsandbox-okypp
答案 2 :(得分:0)
我将代码更改为此:
import React, { useState, useEffect } from "react";
import "./App.css";
import PokeList from "./components/PokeList";
import Paginator from "./components/Paginator";
import axios from "axios";
function App() {
let [pokemons, setPokemons] = useState([]);
let [status, setStatus] = useState(false);
useEffect(
() =>
axios.get("https://pokeapi.co/api/v2/pokemon").then((res) => {
/* setStatus(true);
console.log(status); */
setPokemons(res.data.results.map((poki) => poki.name));
}),
[]
);
return (
<div className="App">
<PokeList pokemons={pokemons} status={status}></PokeList>{" "}
<Paginator></Paginator>
</div>
);
}
export default App;
现在地图正在工作。有人可以解释为什么吗?我所做的唯一可见更改是删除了axios调用周围的setPokemons(),这是错误的。那是为什么我得到怪异的神奇宝贝变量吗?