[英]React JS is returning undefined when trying to access information from array
I have information stored in a json file that is accessed through axios calls and mock.js and I am able to access my information.我的信息存储在 json 文件中,该文件可通过 axios 调用和 mock.js 访问,并且我能够访问我的信息。 This is the data:
这是数据:
information: {
name: 'Company name',
aboutParagraphs: [
["X"],
["Y"],
["Z"],
["XX"]
],
When I try accessing the whole array, it returns all items.当我尝试访问整个数组时,它会返回所有项目。 However, when I try accessing a single array, say
information.aboutParagraphs[0]
, React returns an error TypeError: Cannot read property '0' of undefined
.但是,当我尝试访问单个数组时,比如
information.aboutParagraphs[0]
,React 返回错误TypeError: Cannot read property '0' of undefined
。
Here is the code:这是代码:
<div className="col-lg-6">
<div className="mi-about-content">
<h3>
{information.name}
</h3>
<p>
{information.aboutParagraphs[0]}
</p>
</div>
</div>
I tried checking other solutions but they all seemed to have either a syntax issue or were using the wrong brackets which isn't the case here - as far as I can tell.我尝试检查其他解决方案,但它们似乎都存在语法问题或使用了错误的括号,据我所知,这里不是这种情况。 What am I missing?
我错过了什么? Is it a syntax issue?
是语法问题吗? Thanks in advance.
提前致谢。
Try this:尝试这个:
{information && information.aboutParagraphs && information.aboutParagraphs[0]}
I don't know for sure without seeing your fetch but these issues usually occur when you try to render some data you are getting asynchronously that has not finished.如果没有看到您的 fetch,我不能确定,但是当您尝试渲染一些您正在异步获取但尚未完成的数据时,通常会出现这些问题。
I realize this is overkill but this will tell you if it is an async issue or not.我意识到这有点矫枉过正,但这会告诉你这是否是异步问题。 If it tries to render even an instant before fetch is complete it will be undefined.
如果它甚至在 fetch 完成之前尝试渲染,它将是未定义的。
What the above line does is check that all 3 of those items exist before it tries to render information.aboutParagraphs[0]上面这行所做的是在尝试呈现 information.aboutParagraphs[0] 之前检查所有 3 个项目是否存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.