简体   繁体   English

当我尝试显示数组中的 Object 时未定义

[英]Object in array is undefined when I try to display it

I'm working with React jS and fetching data from pokeapi.我正在使用 React jS 并从 pokeapi 获取数据。
Here's the data structure from the api (goes to number 5):这是 api 的数据结构(转到第 5 个):

stats  
  0
    base_stat
    effort
    stat
      name
      url
  1
    base_stat
    effort
    stat
      name
      url

Here's my code:这是我的代码:

const minHp = pokemon?.stats[0]?.base_stat * 2 + 110;
const maxHp = pokemon?.stats[0]?.base_stat * 2 + 204;

<td className='pokemon_stats_table_row_element'>
    {minHp}
</td>
<td className='pokemon_stats_table_row_element'>
    {maxHp}
</td>

When I load the page there is an error that says that 'pokemon.stats is undefined' and I don't understand why it doesn't works because the path is correct and existing (i'm displaying other data from the 'stats' array and it works fine.当我加载页面时出现错误提示“pokemon.stats is undefined”,我不明白为什么它不起作用,因为路径正确且存在(我正在显示来自“stats”的其他数据阵列,它工作正常。

You need to use the optional chaining ?您需要使用可选链接? operator also when indexing into the stats object, because that property can return undefined, like this:运算符也在索引到stats object 时,因为该属性可以返回未定义的,如下所示:

const minHp = pokemon?.stats?.[0]?.base_stat * 2 + 110;
const maxHp = pokemon?.stats?.[0]?.base_stat * 2 + 204;

暂无
暂无

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

相关问题 我可以打印状态对象数组,但是当我尝试从数组中的对象访问值时,整个对象未定义 - I can print a state object array, but when I try to access a value from an object in the array, the whole object is undefined 为什么当我尝试在 Next js 的数组中访问 object 时显示未定义 - Why It shows Undefined when I try Access object in array in Next js javascript 当我尝试使用数组时,它显示未定义 - javascript When I try to use a array ,it shows undefined 当我尝试访问javascript数组时,正在填充未定义的值 - Undefined value is being populated when i try to access javascript array 当我尝试通过索引访问数组元素时,它给了我未定义的 - when i try to access array element by index it gives me undefined 当我尝试获取它的特定元素时,React 数组返回未定义 - React array returns undefined when i try to get specific element of it 当我尝试在元素“ pro1”中显示总和时,如何解决此“未定义”问题 - How to fix this 'undefined' when i try to display the sum in the element "pro1' 我尝试访问数组元素但未定义 - I try to access the array elements but get undefined 当我尝试在组件上使用数组方法时,为什么我的数组变量未在我的组件中定义? - Why is my array variable undefined in my component when I try to use array methods on it? 为什么在明确定义对象后尝试打印它时,对象仍未定义? - Why is my object undefined when I try to print it when it is clearly defined?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM