简体   繁体   English

如何修复数据。map 不是 function api

[英]How to fix the data.map not a function api

I'm trying to have and show the data of an api.我正在尝试拥有并显示 api 的数据。

https://pokeapi.co/api/v2/pokemon/1 https://pokeapi.co/api/v2/pokemon/1

I have tried to display the data but it's not working.我试图显示数据,但它不起作用。

PokemonSpecies.js 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 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 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;

I have the json, but when I'm trying to display the name or the abilities of the Pokemon I have this error I have try a lot of things but I'm new on React js... :我有 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) =>(

I guess the problem at below line.我猜问题在下面一行。 Can you please check the response of the API call.您能否检查 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
   });

I see that your code is working fine, the only mistake you made is that, the json variable is not an array.我看到您的代码运行良好,您犯的唯一错误是json变量不是数组。 It has a results key inside which you need to map:它有一个results键,您需要在其中 map:

See this Log:请参阅此日志:

在此处输入图像描述

So you need to do this:所以你需要这样做:

const json = await response.json();
      this.setState({
        data: json.results,
        isLoading: false
      });      

Instead of using only the data .而不是只使用data

Here is the demo Sandbox which I created to see the error: https://codesandbox.io/s/sleepy-jang-psedq这是我创建的用于查看错误的演示沙箱: https://codesandbox.io/s/sleepy-jang-psedq

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM