[英]How to fix the data.map not a function api
我正在嘗試擁有並顯示 api 的數據。
https://pokeapi.co/api/v2/pokemon/1
我試圖顯示數據,但它不起作用。
PokemonSpecies.js
import React from "react";
// import Loader from "./Loader";
import { Card, Col } from "react-bootstrap";
import { Container, Row } from "react-bootstrap";
import CardPokemon from "./containers/CardPokemon";
class PokemonSpecies extends React.Component {
state = {
data: [],
isLoading: false,
abilities: []
};
async componentDidMount() {
const id = this.props.match.params.id;
this.setState({ isLoading: true });
try {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
const json = await response.json();
this.setState({
data: json,
isLoading: false
});
console.log({ json });
} catch (err) {
console.log(err.msg);
this.setState({ isLoading: false });
throw err;
}
}
render() {
const { data } = this.state;
return (
<div className="Pokemon">
<Container>
<Row>
<Col lg="4"></Col>
<Col lg="4">
<CardPokemon data={data} />
</Col>
<Col lg="4"></Col>
</Row>
<Row></Row>
</Container>
</div>
);
}
}
export default PokemonSpecies;
CardPokemon.js
import React from "react";
import DataSinglePokemon from "./DataSinglePokemon";
const CardPokemon = ({ data }) => {
return (
<>
{data.map((info, index) => (
<DataSinglePokemon
key={info + index}
id={info.id}
name={info.name
.toLowerCase()
.split(" ")
.map(letter => letter.charAt(0).toUpperCase() + letter.substring(1))
.join(" ")}
height={info.height}
{...info}
/>
))}
</>
);
};
export default CardPokemon;
DataSinglePokemon.js
import React from "react";
import { Card, Col } from "react-bootstrap";
import "../../App.css";
const DataSinglePokemon = props => {
const { height, name, id } = props;
const urlImage = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png?raw=true`;
return (
<Col lg={3}>
<Card>
<Card.Header>{id}</Card.Header>
<Card.Body className="mx-auto">
<Card.Title> {name} </Card.Title>
<Card.Text>
<img alt={name} src={urlImage} />
<br></br>
Taille : {height}
</Card.Text>
</Card.Body>
</Card>
</Col>
);
};
export default DataSinglePokemon;
我有 json,但是當我嘗試顯示口袋妖怪的名稱或能力時,我遇到了這個錯誤,我嘗試了很多東西,但我是 React js 的新手……:
TypeError: data.map is not a function
CardPokemon
src/components/containers/CardPokemon.js:7
4 |
5 | const CardPokemon =({data}) =>{
6 |
> 7 | return(
8 |
9 | <>
10 | {data.map((info,index) =>(
我猜問題在下面一行。 您能否檢查 API 呼叫的響應。
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
const json = await response.json();
this.setState({
data: json, // Check the data type of json. It should be in Array.
isLoading: false
});
我看到您的代碼運行良好,您犯的唯一錯誤是json
變量不是數組。 它有一個results
鍵,您需要在其中 map:
請參閱此日志:
所以你需要這樣做:
const json = await response.json();
this.setState({
data: json.results,
isLoading: false
});
而不是只使用data
。
這是我創建的用於查看錯誤的演示沙箱: https://codesandbox.io/s/sleepy-jang-psedq
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.