【问题标题】:Why does my function run before componentDidMount为什么我的函数在 componentDidMount 之前运行
【发布时间】:2021-12-27 22:15:04
【问题描述】:

我正在尝试使用@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": []
      },
      ...
      

【问题讨论】:

  • 有时候数据一定很奇怪。你能告诉我们数据在 .json() 编辑后是什么样子的吗?
  • @nlta 我更新了我的问题...
  • "我收到一个错误,element 未定义。" - 请您发布确切的错误消息吗?
  • "componentDidMount 尚未运行(控制台日志中没有任何内容)。" - 尝试将 console.log 调用放在 setState 调用之前,而不是在它的调用中打回来。 React 将从 setState 调用 iirc 中重新渲染。
  • this.toggle = this.toggle.bind(this); 这个切换没有在任何地方定义?我尝试在本地运行您的代码,但现在出现了您列出的错误。

标签: javascript reactjs self-reference


【解决方案1】:

两个问题

  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>);

&lt;Submenu..&gt; category.children.forEach(... &lt;/Submenu&gt; 是 jsx 的一部分,实际上这里只调用了一次推送,而不是两次。

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • null == undefined => true,这不是问题
    猜你喜欢
    • 2017-06-30
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多