为什么我的函数 运行 在 componentDidMount 之前

Why does my function run before componentDidMount

我正在尝试使用 @szhsin/react-menu 创建菜单。我收到 element 未定义的错误。 componentDidMount 还没有 运行(控制台日志中没有)。我原以为我的 if (this.state.Categories == null) 会在 AddMenu 被调用之前捕获。

import Config from 'config';
import { Nav, NavItem, Dropdown, DropdownItem, DropdownToggle, DropdownMenu, NavLink } from 'reactstrap';
import { Menu, MenuItem, MenuButton, SubMenu } from '@szhsin/react-menu';
import '@szhsin/react-menu/dist/index.css';
import '@szhsin/react-menu/dist/transitions/slide.css';
import React, { useState } from 'react';

class GetCategories extends React.Component {
    constructor() {
        super();
        this.toggle = this.toggle.bind(this);
        this.state = {
            name: 'React',
            apiData: [],
            isOpen: false,
        };
    }    

    componentDidMount() {
        console.log('app mounted');
        fetch(Config.apiUrl + "/api/Items/GetCategories")
            .then(data => data.json())
            .then(data => this.setState({ Categories: data }, () => console.log(data)));
    }    

    render() {
        var catList = this.state.Categories;
        let categoriesStyled = [];

        function AddMenu(category) {
            if (category.children.length !== 0) {
                console.log(category)
                categoriesStyled.push(<SubMenu label={category.name}>);
                category.children.forEach(element => AddMenu(element) );
                categoriesStyled.push(</SubMenu>);
            }
            else {
                categoriesStyled.push(<MenuItem>{category.name}</MenuItem>);
            }
        }


        if (this.state.Categories == null) {
            console.log("NULL");
            return (
                <div>
                    <h1>{/*ERROR*/}</h1>
                </div>
            );
        }
        else {

            for (let i = 0; i < catList.length; i++) {
                if (catList[i].name !== undefined) {
                    AddMenu(catList[i]);
                }
            }            

            return (
                <div>                    
                    <Menu direction={'bottom'} menuButton={<MenuButton>Shop</MenuButton>} transition>
                        <>
                            {categoriesStyled}
                        </>
                    </Menu>                        
                </div>
            );
        }

    }
}
export default GetCategories;

我确定这是我的愚蠢错误,但我还没有看到。任何帮助将不胜感激。

更新

我的json返回数据:

[
  {
    "categoryId": 3091,
    "parentId": 0,
    "name": "Concrete Services",
    "title": "Concrete Services",
    "description": "Concrete Services",
    "keywords": "Concrete, perfect polish",
    "pageContent": "<span style=\"color:Blue; border-color:Blue; font-weight:bold; font-size:18pt;\">Concrete Services<br/><br/><span style=\"color:#ff6600; border-color:#ff6600; font-size:14pt;\">Perfect Polish provides a wide range of services to fit any need.&edsp;&edsp;Either repair of existing floors, or installation of completely new floors.</span><br/></span>",
    "bannerGroupId": 0,
    "inactive": false,
    "issitecategory": false,
    "sortOrder": null,
    "children": [
      {
        "categoryId": 3092,
        "parentId": 3091,
        "name": "Concrete Polishing",
        "title": "Concrete Polishing",
        "description": "Concrete Polishing",
        "keywords": "polish, polishing",
        "pageContent": "<span style=\"color:Red; border-color:Red; font-style:italic; font-weight:bold; font-size:16pt;\">Concrete Polishing</span><br/><br/>Perfect Polish is the industry leader specializing in polished concrete floors. Our company has performed work across the country for all types of industrial, commercial, and retail facilities. <br/><br/>We perform new construction, facility improvement projects, and provide assistance from pour to completion to insure each project meets our customer expectations.",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3094,
        "parentId": 3091,
        "name": "Repair and Restoration",
        "title": "Repair and Restoration",
        "description": "Repair and Restoration of existing Concrete floors",
        "keywords": "repair, restore, restoration",
        "pageContent": "<span style=\"color:Navy; border-color:Navy; font-weight:bold;\">Repair &amp; Restoration</span><br/>Perfect Polish has years of experience improving facilities with damaged floors. Our team will assess your floors and determine the amount of repair required to bring your floor back to life. Repair and restoration can include cracked concrete, pop-outs, spalling, joint damage, coating removal and more.",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3093,
        "parentId": 3091,
        "name": "Resinous Flooring",
        "title": "Resinous Flooring",
        "description": "Resinous Flooring",
        "keywords": "resinous, resin",
        "pageContent": "<span style=\"color:#ff6600; border-color:#ff6600; font-size:14pt;\">Resinous Flooring</span><br/><br/>Perfect Polish provides resinous flooring services for customers with new and existing facilities across the United States. We offer a wide range of resinous flooring options including <span style=\"font-style:italic;text-decoration: underline;\">epoxy, urethane, and acrylic materials, decorative options, line striping, border painting, and more.</span>",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      }
    ]
  },
  {
    "categoryId": 1005,
    "parentId": 0,
    "name": "Electrics",
    "title": "Electrics",
    "description": "Electrics",
    "keywords": "Electrics",
    "pageContent": "Electrics <span style=\"color:#33cccc; border-color:#33cccc; font-weight:bold;\">- page of information</span>",
    "bannerGroupId": 0,
    "inactive": false,
    "issitecategory": false,
    "sortOrder": null,
    "children": [
      {
        "categoryId": 1006,
        "parentId": 1005,
        "name": "FloodLights",
        "title": "FloodLights",
        "description": "FloodLights",
        "keywords": "FloodLights",
        "pageContent": "FloodLights",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 1007,
        "parentId": 1005,
        "name": "Light",
        "title": "Lights",
        "description": "Lights",
        "keywords": "Lights",
        "pageContent": "Lights",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3095,
        "parentId": 1005,
        "name": "Motors",
        "title": "Electric Motors",
        "description": "Electric Motors",
        "keywords": "Electric Motors, Motors",
        "pageContent": "<span style=\"font-weight:bold;\">Electric Motors</span><span style=\"color:#33cccc; border-color:#33cccc; font-weight:bold;\">- Provided by Kinney Electric &amp; Power Transmission</span>",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      }
    ]
  },
  {
    "categoryId": 3056,
    "parentId": 0,
    "name": "Fasteners",
    "title": "Fasteners",
    "description": "Fasteners",
    "keywords": "Anchors, bolts, hardware, nails, nuts, pins, clips, rivets, rods, screws, sockets, clamps, hangers, washers",
    "pageContent": "<p style=\"text-align:Left;\"><span style=\"border-color:Red; font-weight:bold; font-size:12pt;\"><span style=\"color:Blue; border-color:Blue;\">FASTENERS</span><br/>Same Day Shipping On Bulk Industrial Fasteners</span><br/><span style=\"color:Blue; border-color:Blue; font-style:italic;\">The Fastener Superstore is your one stop shop for nuts,<span style=\"color:Red; border-color:Red;\"> bolts, washers, rivets, standoffs and mo</span>re! <br/>We have <span style=\"text-decoration: underline;\">everything</span> you need right here.&edsp;</span><br/>* 34,000+ Distinct Parts<br/>* All Pricing Online<br/>* No Registration Required<br/>* Same Day Shipping on Most Orders<br/>* Order online, via phone, email or fax<br/>* Extended Customer Service Hours (7am-7pm CT)<br/>* Quotes Available for Larger <span style=\"color:#3366ff; border-color:#3366ff;\">Quantities</span></p>",
    "bannerGroupId": 0,
    "inactive": false,
    "issitecategory": false,
    "sortOrder": null,
    "children": [
      {
        "categoryId": 3057,
        "parentId": 3056,
        "name": "Bolts",
        "title": "Bolts",
        "description": "Bolts",
        "keywords": "Bolts, Carraige, Dowel, Hanger, Elevator",
        "pageContent": "<span style=\"font-style:italic; font-weight:bold;\">The quality of the bolt you use can determine the integrity of the entire structure</span> — whether it’s a building project or a piece of machinery. Builders and contractors looking to buy wholesale nuts and bolts know they can trust Fastener <span style=\"color:Red; border-color:Red;text-decoration: underline;\">SuperStore to have the most comprehensive selection. </span>We are known for providing only the highest quality fastener hardware specific to whatever your application may be. See our list of bolt products and some common uses below, as well as information about what Fastener SuperStore can do for you.",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3096,
        "parentId": 3056,
        "name": "MKT",
        "title": "MKT",
        "description": "MKT Fasteners",
        "keywords": "MKT",
        "pageContent": "",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3069,
        "parentId": 3056,
        "name": "Nails",
        "title": "Nails",
        "description": "Nails",
        "keywords": "Nails",
        "pageContent": "",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      ...
      

this.state.Categories 未定义,不为空。您应该尝试 if(!this.state.Categories) 而不是 if(this.state.Categories == null)

两个问题

  1. this.toggle 未定义 所以 this.toggle = this.toggle.bind(this); 是错误的
  2. 您将 JSX 元素推入数组,就像构建字符串一样。它们不是字符串。事实上,您在这里创建了一个 JSX 元素,其中包含一些您认为是代码的东西。
                categoriesStyled.push(<SubMenu label={category.name}>);
                category.children.forEach(element => AddMenu(element) );
                categoriesStyled.push(</SubMenu>);

<Submenu..> category.children.forEach(... </Submenu> 都是 jsx 的一部分,实际上这里只调用了一个推送,而不是两个。

它应该是带有子元素的单个元素,而不是开始/子/结束元素。

categoriesStyled.push(
    <SubMenu label={category.name}>
        {category.children.forEach(element => AddMenu(element)}
    </SubMenu>)

当我删除 this.toggle 行并修复推送时,您的代码工作正常。