[英]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.