在 React Big Calendar 中直接使用设置状态更新事件时遇到问题

trouble using set state correctly to update an event in react Big Calender

我正在尝试实现 React 大日历,但是我在添加事件和使用设置状态更新 event.I 创建我的日历组件然后使用句柄 select 函数时遇到问题接受新事件并设置状态,但我不确定如何正确设置状态。设置状态的文档使用渲染,但我不使用渲染来显示日历。我不确定我在哪里需要构造函数方法或者我可能缺少什么。

当前错误是

TypeError: 无法读取未定义的 属性 'setState'

import React, { useState } from "react";
import "react-big-calendar/lib/css/react-big-calendar.css";
import Navigation from "../components/Navigation";
import events from "./events";
import { Calendar, momentLocalizer } from "react-big-calendar";
import moment from "moment";

const localizer = momentLocalizer(moment);

const handleSelect = ({ start, end }) => {
  const title = window.prompt("New Event name");

  alert("title " + title);

  if (title) {
    this.setState({
      events: [
        this.state.events,
        {
          start,
          end,
          title,
        },
      ],
    });

    console.log(events);
  }
};

const MyCalendar = (props) => (
  <div>
    <Navigation />
    <Calendar
      selectable
      localizer={localizer}
      events={events}
      popup
      startAccessor="start"
      endAccessor="end"
      style={{ height: 700 }}
      onSelectSlot={handleSelect}
    />
  </div>
);
export default MyCalendar;

关键字this在函数式编程的世界里什么都不做。这是OOP的一个概念。不要混淆它们。

相反,执行以下操作

import { useState } from "react";
import moment from "moment"; // bad practice BTW, moment is huge. You should only import the part you need instead of the entire package

const MyCalendar = props => {
  const [events, setEvents] = useState([]);

  const handleSelect = ({ start, end }) => {
    const title = window.prompt("New Event name");

    alert("title " + title);

    if (title) {
      // add a new event
      setEvents(events => ([
        ...events,
        {
          start,
          end,
          title
        }
      ]))

      // setState is async, outputting the events here will most likely return the old value
      console.log(events);
    }
  };

  return (
    <div>
      <Navigation />
      <Calendar
        selectable
        localizer={localizer}
        events={events}
        popup
        startAccessor="start"
        endAccessor="end"
        style={{ height: 700 }}
        onSelectSlot={handleSelect}
      />
    </div>
  )
};
export default MyCalendar;