简体   繁体   English

React js app - 使用 class 组件中 function 的返回值设置功能组件的 state (错误:未定义)

[英]React js app - setting functional component's state with a returned value from function in class component (error: undefined)

I have a calendar app in React with backend created from an existing calendar app in ASP.NET Core.我在 React 中有一个日历应用程序,其后端是从 ASP.NET Core 中的现有日历应用程序创建的。 I configured the proxy and the API works fine, I can log the contents which were imported through fetch.我配置了代理,API 工作正常,我可以记录通过 fetch 导入的内容。 To store and parse data from JSON I created classes MonthOfEvents and Event (for each day of the month there is an array of events).为了存储和解析来自 JSON 的数据,我创建了 MonthOfEvents 和 Event 类(每个月的每一天都有一系列事件)。 Here is the MonthOfEvents class:这是 MonthOfEvents class:

import { getYear, getMonth, getDaysInMonth } from 'date-fns'
import Event from './Event'

class MonthOfEvents {

    // contains lists of events for each day of the month
    constructor(year, month) {
        // if year and month not specified - use current month
        if(!year || !month) {
            const today = new Date()
            this.year = getYear(today)
            this.month = getMonth(today)
        }
        else {
            // add error handling
            this.year = year
            this.month = month
        }

        this.events = [null]
        // array of arrays of events - an array for each day of the month
        for(let i = 0; i < getDaysInMonth(new Date(year, month, 1)); i++) {
            (this.events).push([])
        }
    }

    static getFromJSON(json) {
        let eventsArray = new MonthOfEvents(json.year, json.month)
        console.log("eventsArray.year: " + eventsArray.year)
        console.log("eventsArray.month: " + eventsArray.month)
        console.log("eventsArray.events: " + eventsArray.events)

        for(let i = 0; i <= json.events.length; i++) {
            for(let j = 0; j < json.events[i].length; j++) {
                const id = json.events[i][j].id
                const description = json.events[i][j].description
                eventsArray.events[i].push(new Event(id, new Date(0), description))
            }
        }
        console.log("getFromJSON: eventsArray: "+eventsArray)
        return eventsArray
    }

}

export default MonthOfEvents

Event class doesn't matter for now, but these are normal classes and all others are functional components.事件 class 暂时不重要,但这些是普通类,所有其他都是功能组件。 I created a state for the monthOfEvents and during the first fetch I'm trying to set that state to what getFromJSON function in MonthOfEvents class returns. I created a state for the monthOfEvents and during the first fetch I'm trying to set that state to what getFromJSON function in MonthOfEvents class returns. The problem is: the events list from data variable in this MonthOfEvents is undefined and I can't figure out why.问题是:这个 MonthOfEvents 中数据变量的事件列表是未定义的,我不知道为什么。 Here is part of the App.js component:这是 App.js 组件的一部分:

import React, { useState, useEffect } from 'react';
import Calendar from './Calendar'
import DayEditor from './DayEditor'
import EventEditor from './EventEditor'
import { format, getMonth, getDay, getDaysInMonth, getDate, getYear, parseISO} from 'date-fns'
import MonthOfEvents from '../datacomponents/MonthOfEvents';

function App() {

  console.log("render")

  const [year, setYear] = useState(getYear(new Date()))
  const [month, setMonth] = useState(getMonth(new Date()))
  const [currentDate, setCurrentDate] = useState(new Date())
  const [activeComponent, setActiveComponent] = useState(
    <Calendar
      date={currentDate}
      getNextMonth={getNextMonth}
      getPrevMonth={getPrevMonth}
      handlePick={handlePick}
    />)
    const [onPick, setOnPick] = useState(false)
    const [pickedDate, setPickedDate] = useState()
    //const [fetching, setFetching] = useState(false)
    const [monthOfEvents, setMonthOfEvents] = useState( new MonthOfEvents() )

    console.log(currentDate)

    useEffect(() => {
      console.log("FETCH")
      // API call
      fetch(`api/events/${format(currentDate, "yyyy-M")}`)
        .then(response => response.json())
        .then(data => {
          console.log(data)
          setMonthOfEvents(MonthOfEvents.getFromJSON(data))
        })
    }, [currentDate])

Example of the output from API (just from logging the data object in fetch):来自 API 的 output 示例(仅来自在获取中记录数据 object):

{status: "ok", year: 2020, month: 6, events: Array(31)}
events: (31) [Array(0), Array(0), Array(0), Array(2), Array(0), Array(1), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0), Array(0)]
month: 6
status: "ok"
year: 2020

I am stuck because of this error:由于此错误,我被卡住了:

Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
    at Function.getFromJSON (MonthOfEvents.js:45)
    at eval

and it occurs because of this line:它是因为这条线而发生的:

setMonthOfEvents(MonthOfEvents.getFromJSON(data))

It's my first project in React and I have no idea what to do about this problem.这是我在 React 中的第一个项目,我不知道如何解决这个问题。

Your first loop is going too far because array index starts at 0 and ends at arraySize -1.您的第一个循环太过分了,因为数组索引从 0 开始并以 arraySize -1 结束。 Therefore, in your last loop (i == json.events.length), your json.events[i] is undefined which throws the error message (undefined does not have length method).因此,在您的最后一个循环中(i == json.events.length),您的 json.events[i] 是undefined的,它会引发错误消息(未定义没有length方法)。

To fix this, replace the operator <= by <要解决此问题,请将运算符<=替换为<

 for(let i = 0; i < json.events.length; i++) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应:在功能组件中更改 State 也更改功能组件的道具值,及其父 Class State - React: Changing State in functional component also Change functional component's props value, and its Parent Class State React Native - Class 组件到功能组件(UseEffect:state 未定义) - React Native - Class Component to Functional Component (UseEffect: state undefined) 将 React 类组件的状态迁移到功能组件 - Migrating a React class component's state to a functional component React Native:从 class 调用功能组件内部的 function - React Native: Calling a function that's inside a functional component from a class 反应:从功能组件内部在容器中设置状态 - React: setting state in container from within functional component 在反应js中单击按钮时从class组件导航到功能组件 - Navigate from class component to functional component on button click in react js 使用异步状态设置从类转换为功能组件 - Converting from class to functional component with async state setting 如何在 react.js ZA2F2ED4F8EBC2ABC61ZDC4 中的另一个 function 组件中设置相同的 state 变量后立即访问 state 值 - how to access state value right after setting the same state variable in another function in react.js class component 为什么我的功能组件的 state 未定义? - Why is my functional component's state undefined? 在功能组件中设置 state 是说 setState 不是 function - Setting a state in a functional component is saying the setState is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM