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