简体   繁体   English

React.js - 无法访问对象数组中元素的值

[英]React.js - Can't access an element's value in an Array of Objects

I feel like a lousy developper coming to you with that question but I'm going in circles.我觉得自己是一个糟糕的开发人员,带着这个问题来找你,但我在兜圈子。

I'm using React/JS and here's the problem :我正在使用 React/JS,这是问题所在:

The code imports an array of objects from my personnal API via ajax (axios) .该代码通过 ajax (axios)从我的个人 API 导入了一组对象
My state expect an array : const [ films, setFilms ] = useState([]);我的状态需要一个数组: const [ films, setFilms ] = useState([]); and receives one.并收到一个。

Indeed, the response.result from my API is an array of 20 movie objects :实际上,来自我的 API 的response.result是一个包含 20 个电影对象数组

在此处输入图片说明

I just want to pass it as props to another component in which I'm gonna use one of the object stored in the array to use and display its values but I've been unable to do so...so far.我只是想将它作为道具传递给另一个组件,在该组件中我将使用存储在数组中的对象之一来使用和显示其值,但我一直无法这样做......到目前为止。

Now, in React, when I test to call one movie like this :现在,在 React 中,当我测试像这样调用一部电影时:
console.log("films", films); => WORKS (shows screen capture above) , => WORKS (显示上面的屏幕截图)
console.log("film", films[0]); => WORKS (shows first element, an object) , => WORKS (显示第一个元素,一个对象)

But if I try to enter it (any properties) :但是,如果我尝试输入它(任何属性)
console.log("film", films[0].id); OR console.log("film", films[0]["id"]);console.log("film", films[0]["id"]);
=> FAILS : TypeError: films[0] is undefined ! =>失败:类型错误:电影 [0] 未定义

I know I'm missing something.我知道我错过了一些东西。 I receive an array of object, can enter an element but can't read its properties...我收到一个对象数组,可以输入一个元素但无法读取其属性...

I feel lost... Help ?我感到迷茫...帮助? :) :)
Thank you谢谢

尝试像这样使用&&运算符:

console.log("film", films[0] && films[0].id);

Probably your console.log("films", films);可能是你的console.log("films", films); method is called a couple of times even films are not loaded yet.即使电影尚未加载,方法也会被调用几次。 When you try to log films it will first log null or an empty array, but then it will show the correct list.当您尝试记录电影时,它首先会记录 null 或空数组,但随后会显示正确的列表。 On the other hand, when you have console.log("film", films[0].id);另一方面,当你有console.log("film", films[0].id); , your app will crash because it was called while films array is null or empty. ,您的应用程序将崩溃,因为它是在电影数组为 null 或为空时调用的。

So make sure that your film array length is greater than 0 before logging.所以在记录之前请确保您的胶片阵列长度大于 0。

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

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