英文:
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 "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>
</>
);
}
答案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 "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>
)
}
</>
);
}
答案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(()=>{
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=''
if(results) typesItem = result.types.map((item) => <p>{item.type.name}</p>)
console.log(typesItem)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论