简体   繁体   English

尝试使用React访问数组内的对象时出错

[英]Error when trying to access an object inside an array with React

I'm trying to access a property on an array that has on index 0 an object and I'm trying the following: object[0].main But the console throws me an error. 我正在尝试访问具有索引0的对象的数组上的属性,并且正在尝试以下操作: object[0].main但是控制台向我抛出错误。

I'm using React on codepen so it doesn't show me the error pretty well, I want to access that property to be able to put it on another object that I'll pass down as props (because is something I hold on my state). 我在Codepen上使用React,所以它不能很好地显示错误,我想访问该属性以便能够将其放置在另一个我将作为道具传递的对象上(因为这是我持有的东西)州)。 Here is my code: https://codepen.io/manAbl/pen/aGymRg?editors=0011 Look for line 56. This is stressing me out. 这是我的代码: https : //codepen.io/manAbl/pen/aGymRg? editors =0011查找第56行。这让我感到压力。 Thanks in advance 提前致谢

This happens because the data is not loaded from the server yet so the object will be initially as you set it to {} 发生这种情况是因为尚未从服务器加载数据,因此该对象最初是在将其设置为{}时

so to fix this you can do 为了解决这个问题,你可以做

instead of 代替

description: this.state.weather.weather[0].main,

do

description: this.state.weather.weather && this.state.weather.weather[0].main,

The idea is you set the initial state to : {} correct? 想法是您将初始状态设置为:{}对吗? and render is called before the ajax is actually finished since its async. 自从ajax异步完成以来,render在其实际完成之前被调用。

so on first render it will be "{}" and you are doing [0].main on it. 因此在第一次渲染时它将是“ {}”,并且您正在对其进行[0] .main。 which will crash. 将会崩溃。

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

相关问题 试图在 object 反应的数组内创建 object - trying to create object inside array of an object react 错误在对象内部访问数组时无法读取未定义的属性“ 1” - error Cannot read property '1' of undefined when access array inside an object 对象内部的访问数组[React] JavaScript - Access array inside of object [React] javascript React 无法访问数组内部 Object - React Can't Access Array Inside Object 尝试更新 object 内部的 object 中的数组。 反应,使用状态 - Trying to update an array in an object inside of an object. React, useState 尝试访问对象中的SVG时Chrome出现错误 - Error on chrome when trying to access svg in object 尝试访问 React state 变量中的嵌套数组时如何解决未定义错误? - How to solve undefined error when trying to access a nested array in a React state variable? 我正在尝试访问数组内部对象中的图像 - I'm trying to access an image that is in an object inside of an array JSON 解析错误:尝试解析数组中的对象时出现意外的标识符“未定义”(React-Native) - JSON Parse error: Unexpected identifier "undefined" when trying to parse an object from an array (React-Native) IndexedDB:尝试访问表内的嵌套 object 时出现 SchemaError - IndexedDB: SchemaError when trying to access nested object inside a table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM