简体   繁体   中英

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. 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 .

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.

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.

What the above line does is check that all 3 of those items exist before it tries to render information.aboutParagraphs[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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