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

huangapple go评论66阅读模式
英文:

Array within JSON manipulation issues using map method

问题

我正在构建一个类似宝可梦百科的页面作为初学者项目。我想从我通过axios获取的JSON对象中呈现出宝可梦的类型。然而,我似乎无法正确地在对象中返回的类型数组上使用map方法。

目前,我正在尝试将typesItem常量设置为映射的<p>元素,然后将其放入我的属性列表中。
但是我遇到了这个错误Pokemon.jsx:30 Uncaught TypeError: Cannot read properties of undefined (reading 'map')。因此,我认为错误出现在第30行。几乎可以肯定是因为我搞错了如何访问JSON对象的某些部分。

英文:

I am building a pokemon wiki-type page as a beginner project. I want to render out the pokemon's types from the json object I am getting via axios. However, I cannot seem to properly use the map method on the types array returned in the object.

Currently, I am trying to set the typesItem const to be the mapped <p> elements and then just slap that in my list of attributes.
I get this error however Pokemon.jsx:30 Uncaught TypeError: Cannot read properties of undefined (reading 'map'). So i think the error is in my line 30. and it's almost definitely because I'm messing up how to access certain parts of json objects.

Use this to view the json api https://pokeapi.co/

import React from &quot;react&quot;;

import axios from &quot;axios&quot;;
import &quot;../styles/pokemon.css&quot;;

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

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

  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) =&gt; &lt;p&gt;{item.type.name}&lt;/p&gt;);

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

答案1

得分: 1

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(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(result);
    } catch (error) {
      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>
      {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>
      )}
    </>
  );
}
英文:

Short on time at the moment, but the below snippet should fix your issue (some comments contained within).

import React from &quot;react&quot;;

import axios from &quot;axios&quot;;
import &quot;../styles/pokemon.css&quot;;

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

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

  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 (
    &lt;&gt;
      &lt;div className=&quot;pokemon-input-container&quot;&gt;
        &lt;h3&gt;Search for Details about your Favorite Pokemon!&lt;/h3&gt;
        &lt;br&gt;&lt;/br&gt;
        &lt;input
          className=&quot;pokemon-input&quot;
          type=&quot;text&quot;
          placeholder=&quot;Input Pokemon Name&quot;
          onChange={(e) =&gt; setInputPokemon(e.target.value)}
          onKeyDown={handleKeyDown}
          value={inputPokemon}
        /&gt;
      &lt;/div&gt;
      {
        // 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&#39;s either undefined
        // or an object it shouldn&#39;t be a problem.
        //
        // Now nothing else will be run on result unless it has been populated, problem solved.
        result &amp;&amp; (
          &lt;div className=&quot;pokemon-output-container&quot;&gt;
            &lt;div className=&quot;name&quot;&gt;Name: {result.name}&lt;/div&gt;
            &lt;div className=&quot;type&quot;&gt;Type: {result.types.map((item) =&gt; &lt;p&gt;{item.type.name}&lt;/p&gt;)}&lt;/div&gt;
            &lt;div className=&quot;weight&quot;&gt;
              Weight: {result.weight} Height: {result.height}&quot;
            &lt;/div&gt;
            &lt;div className=&quot;moves&quot;&gt;Possible Moves: &lt;/div&gt;
            &lt;div className=&quot;stats&quot;&gt;Stats:&lt;/div&gt;
            &lt;div className=&quot;abilities&quot;&gt;Abilities: &lt;/div&gt;
          &lt;/div&gt;
        )
      }
    &lt;/&gt;
  );
}

答案2

得分: 0

请检查是否输出以下内容:

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

如果输出为undefined则可能是数据库调用出现了问题

好的既然有结果尝试这样做

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

如果您需要进一步的帮助,请告诉我。

英文:

Try inserting this and tell me if it's outputting:

useEffect(()=&gt;{
     console.log(result)
},[result])

If this is outputting undefined then something is wrong in your Database call

Ok, since there's a result, try this:

let typesItem=&#39;&#39;
if(results) typesItem = result.types.map((item) =&gt; &lt;p&gt;{item.type.name}&lt;/p&gt;)
console.log(typesItem)

huangapple
  • 本文由 发表于 2023年5月15日 07:02:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定