reactjs 使用map方法处理JSON中的数组问题

sxissh06  于 2023-05-17  发布在  React
关注(0)|答案(2)|浏览(106)

我正在建立一个口袋妖怪维基类型的页面作为一个初学者项目。我想从我通过axios得到的json对象中呈现出口袋妖怪的类型。但是,我似乎无法正确地对对象中返回的类型数组使用map方法。
目前,我正在尝试将typesItem常量设置为Map的
元素,然后将其放入属性列表中。我得到这个错误然而Pokemon.jsx:30 Uncaught TypeError:无法读取未定义的属性(阅读“map”)。所以我认为错误在我的第30行。几乎可以肯定是因为我搞砸了如何访问JSON对象的某些部分。
使用此命令查看json API https://pokeapi.co/

import React from "react";

import axios from "axios";
import "../styles/pokemon.css";

export default function Pokemon() {
  const [inputPokemon, setInputPokemon] = React.useState("");
  const [result, setResult] = React.useState({});

  function handleKeyDown(e) {
    if (e.key == "Enter") {
      fetchPokemon();
      setInputPokemon("");
    }
  }

  async function fetchPokemon() {
    try {
      const response = await axios.get(
        `https://pokeapi.co/api/v2/pokemon/${inputPokemon.toLowerCase()}`
      );

      setResult(response.data);
      //   console.log(response.data);
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  }
  const typesItem = result.types.map((item) => <p>{item.type.name}</p>);

  return (
    <>
      <div className="pokemon-input-container">
        <h3>Search for Details about your Favorite Pokemon!</h3>
        <br></br>
        <input
          className="pokemon-input"
          type="text"
          placeholder="Input Pokemon Name"
          onChange={(e) => setInputPokemon(e.target.value)}
          onKeyDown={handleKeyDown}
          value={inputPokemon}
        />
      </div>
      <div className="pokemon-output-container">
        <div className="name">Name: {result.name}</div>
        <div className="type">Type: {typesItem}</div>
        <div className="weight">
          Weight: {result.weight} Height: {result.height}"
        </div>
        <div className="moves">Possible Moves: </div>
        <div className="stats">Stats:</div>
        <div className="abilities">Abilities: </div>
      </div>
    </>
  );
}
tpgth1q7

tpgth1q71#

目前时间很短,但下面的片段应该可以解决您的问题(其中包含一些评论)。

import React from "react";

import axios from "axios";
import "../styles/pokemon.css";

export default function Pokemon() {
  const [inputPokemon, setInputPokemon] = React.useState("");
  // use undefined instead of empty object (easier to run conditions on).
  const [result, setResult] = React.useState(undefined);

  function handleKeyDown(e) {
    if (e.key == "Enter") {
      fetchPokemon();
      setInputPokemon("");
    }
  }

  async function fetchPokemon() {
    try {
      const response = await axios.get(
        `https://pokeapi.co/api/v2/pokemon/${inputPokemon.toLowerCase()}`
      );

      setResult(response.data);
      //   console.log(response.data);
      console.log(result);
    } catch (error) {
      // When error clear data.
      setResult(undefined);
      console.error(error);
    }
  }

  return (
    <>
      <div className="pokemon-input-container">
        <h3>Search for Details about your Favorite Pokemon!</h3>
        <br></br>
        <input
          className="pokemon-input"
          type="text"
          placeholder="Input Pokemon Name"
          onChange={(e) => setInputPokemon(e.target.value)}
          onKeyDown={handleKeyDown}
          value={inputPokemon}
        />
      </div>
      {
        // check if result exists, if you are worried about result being a falsy value
        // that react will display slap two bangs on it (!!result) but if it's either undefined
        // or an object it shouldn't be a problem.
        //
        // Now nothing else will be run on result unless it has been populated, problem solved.
        result && (
          <div className="pokemon-output-container">
            <div className="name">Name: {result.name}</div>
            <div className="type">Type: {result.types.map((item) => <p>{item.type.name}</p>)}</div>
            <div className="weight">
              Weight: {result.weight} Height: {result.height}"
            </div>
            <div className="moves">Possible Moves: </div>
            <div className="stats">Stats:</div>
            <div className="abilities">Abilities: </div>
          </div>
        )
      }
    </>
  );
}
rsl1atfo

rsl1atfo2#

尝试插入此命令并告诉我它是否正在输出:

useEffect(()=>{
     console.log(result)
},[result])

如果输出的是undefined,那么数据库调用中有问题
好吧,既然有结果,试试这个:

let typesItem=''
if(results) typesItem = result.types.map((item) => <p>{item.type.name}</p>)
console.log(typesItem)

相关问题