简体   繁体   English

React Hooks - 无法从状态中获取嵌套数据

[英]React Hooks - Can't get nested data from state

I'm still having difficulty with my state "pokeData".我的状态“pokeData”仍然有困难。 I'm calling pokeapi and setting the state and am able to obtain 1 level of nested data, anything more and I get an error and my state becomes undefined.我正在调用 pokeapi 并设置状态,并且能够获得 1 级嵌套数据,其他任何内容都会出现错误并且我的状态变得未定义。 Below is a pic of the console and what the data structure shows.下面是控制台的图片和数据结构显示的内容。

My problem is at this line code: `我的问题是在这一行代码:`

 <img src={pokeData.sprites.front_default} alt=""/>

` `

 import React, { useState, useEffect } from 'react'; import axios from 'axios'; const Card = () => { const [ pokeData, setPokeData ] = useState([]); useEffect(() => { axios .get('https://pokeapi.co/api/v2/pokemon/151') .then(res => { setPokeData(res.data); }) .catch(err => { console.log(err); }) }, []); console.log(pokeData); return ( <div className="card"> <h1 className="poke-name">{pokeData.name}</h1> <img src={pokeData.sprites.front_default} alt=""/> </div> ) } export default Card;

Console Error控制台错误

Data in "pokeData" state “pokeData”状态下的数据

Your pokeData is received via asynchronous action so by the time of rendering, your data may not be set yet.您的pokeData是通过异步操作接收的,因此在渲染时,您的数据可能尚未设置。

You can check the availability of your data before actually rendering您可以在实际渲染之前检查数据的可用性

{ (pokeData && pokeData.sprites) &&
   <img src={pokeData.sprites.front_default} alt=""/>
}

working example: link - sandbox using optional_chaining工作示例:链接 - 使用 optional_chaining 的沙箱

setPokeData will be asynchronous and the data availability in pokeData is going to take some time. setPokeData 将是异步的,pokeData 中的数据可用性需要一些时间。 Since pokeData's initial value is empty array [] , this {pokeData.sprites.front_default} would be {[].sprites.front_default} and you get undefined error.由于 pokeData 的初始值是空数组[] ,这个{pokeData.sprites.front_default}将是{[].sprites.front_default}并且你得到未定义的错误。

you could use optional chaining operator (?.) to safely ignore if the key value is not available in the object.如果键值在对象中不可用,您可以使用可选链运算符 (?.)来安全地忽略。

<img src={pokeData?.sprites?.front_default} alt=""/>

ref:参考:

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

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