0

Пытаюсь создать компоненту меню. Поступающий объект может иметь разную вложенность groups(в тестовом объекте 3 увроня). При загрузке страницы я пытаюсь вызвать метод, который генерирует текущие итемы ( нужно отрисовать 2 уровня: первый и второй, который будет являться подуровнем), но он ругается на menu_items : this.getMenuItems(this.state.items);

Пишет:

Cannot read property 'items' of undefined

В чем может быть ошибка?

Код компоненты:

class Menu extends Component {

    constructor(props) {
        super(props);

        this.state = {
            level_counter : 0,
            items         : [
            {
                'id' : 1,
                'title' : 'Dashboard',
                'groups' : [
                    {
                        'id' : 2,
                        'title' : ' Group 1',
                        'groups' : [],                  
                    },
                    {
                        'id' : 3,
                        'title' : 'Measure Group 2',
                        'groups' : [
                            {
                                'id' : 4,
                                'title' : 'Group 4',
                                'groups' : [],
                            }
                        ],
                    }
                ]
            }
        ],
        menu_items    : this.getMenuItems(this.state.items),
        };

    }


    render() {
        let { items,menu_items } = this.state;

        console.log(this.state.items)
        return (
            <div className='menu-container'>
                <ul className='menuItems-list'>
                    <li className='menuItem'>
                        <a>
                            <Icon className='menuItem-iconBack' name='caret left' size='small'/> Back
                        </a>
                    </li>
                    {menu_items}
                </ul>
            </div>
        )
    }

    getMenuItems = ( items ) => {
        let { menu_items } = this.state;

        for(let group in  items) {
            menu_items.push(
                <MenuItem         key     = {items[group].id}
                                  item    = {items[group]}
                                  onClick = { this.menuItemClick }
                />
            );
            if (items[group].groups.length > 0 && this.state.level_counter != 0) {
                this.setState({level_counter: this.state.level_counter + 1})
                this.getMenuItems(items[group].groups)
            }
        }
        return menu_items;
    };

    menuItemClick = itemId => {
        let { items } = this.state;
        this.setState({level_counter: 0});
        this.getCurrentMenuLevel( items, itemId);
    };

    getCurrentMenuLevel = ( items,itemId ) => {

        for(let item in items){
            if (items[item].id != itemId ) {
                this.getCurrentMenuLevel ( items[item].groups,itemId);
            } else {
                this.getMenuItems (items[item].groups);
            }
        }
    };

}


export default Menu;

1 ответ 1

1

Потому что вы в переменной this.state пытаетесь присвоить значение, которое содержить ссылку на this.state, которая в момент присваивания равно undefined. Нужно удалить menu_items из state

    this.state = {
        level_counter: 0,
        items: [{
            'id': 1,
            'title': 'Dashboard',
            'groups': [{
                    'id': 2,
                    'title': ' Group 1',
                    'groups': [],
                },
                {
                    'id': 3,
                    'title': 'Measure Group 2',
                    'groups': [{
                        'id': 4,
                        'title': 'Group 4',
                        'groups': [],
                    }],
                }
            ]
        }],
    };
1
  • рекомендую пользоваться отладчиком (дебагером) для определения какая переменная чему равняется в рантайме 18 дек 2017 в 13:17

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.