Error accessing property with map function

Asked

Viewed 78 times

-2

When I try to access the property this.props.arrayMenu shows me the following error:

Uncaught Typeerror: Cannot read Property 'id' of Undefined.

as shown below: loop erro dados

import React , { Component } from 'react';

export default class Categorais extends Component
{
    render(){
        return(
            <div className="row">
                {                      
                    this.props.arrayMenu.map(function(menuItem, i) {
                    if (menuItem.submenu !== undefined) {
                        return (
                            <ul key={i}>{menuItem.categoria}    
                                {menuItem.submenu.map(function(subMenu, i) {                                   
                                    return <li key={i}>{subMenu.categoria}</li>;
                                })}
                            </ul>
                        )
                    }
                    else
                    {
                        return (
                             <ul key={i}>
                                 <li key={i}>{menuItem.menu.categoria}</li>
                             </ul>
                        )
                    }        
                })
            }
            </div>
        );
    }
}

  • There is no way to know if the "category" of menuItem of his this.props.arrayMenu are Undefined or not. You should check the content of your props. We have no way to guess what you develop and does not show.

1 answer

0

arrayMenu is receiving all data from your API, including objects menu and submenu, when making the map you assign to the jsonMenu the menuItem.menu, this for all items on your list.

Only when you see one subMenu, you assign to jsonMenu the value menuItem.menu, but in the case of subMenu, That doesn’t exist, so it is undefined

You’d have to make one if to check if the property exists menu before assigning it to the jsonMenu, example:

let jsonMenu = {};

if(menuItem.menu) {
  jsonMenu = menuItem.menu;
}

In this case, you always guarantee that there will be the menu before assigning it to the variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.