【问题标题】:Update react-big-calendar component when new event created创建新事件时更新 react-big-calendar 组件
【发布时间】:2020-07-30 17:38:06
【问题描述】:

我正在使用 react-big-calendar,并希望用户能够在将鼠标拖到日历上以根据 create events demonstration 选择日期/时间范围时创建新事件。

但是,我编写的代码不会在成功创建事件时重新渲染组件。用户可以创建一个新事件,如果用户选择另一个视图(例如议程),它将显示 - 然后将出现在所有视图中。但是,根据演示,它不会立即显示在当前视图中。

我很确定这个问题的答案在于 useEffect;但我绕着圈子试图弄清楚。

import React, { useState  } from 'react';
import './App.css';
import 'react-big-calendar/lib/css/react-big-calendar.css';
import { Calendar, momentLocalizer } from 'react-big-calendar'
import moment from 'moment'

function MyCalendar() {
    const localizer = momentLocalizer(moment)
    const [eventsList, setEventsList] = useState([]);

    function handleSelect ({ start, end }) {
        const title = window.prompt('New Event name')
        if (title) {
            var newEvent = {
                start: start,
                end: end,
                title: title 
            }
            let updateEventsList = eventsList;
            updateEventsList.push(newEvent);
            setEventsList(updateEventsList);
        }
    };

    return (
        <div>
        <Calendar
        selectable
        defaultView="week"
        defaultDate={new Date()}
        localizer={localizer}
        events={eventsList}
        startAccessor="start"
        endAccessor="end"
        style={{ height: 500 }}
        onSelectSlot={handleSelect}
        />
        </div>
    )
}

function App() {
    return (
        <div>
        <MyCalendar />
        </div>
    );
}

export default App;

【问题讨论】:

  • 你能添加你的 'react-big-calendar/lib/css/react-big-calendar.css' 和 'react-big-calendar/lib/css/react-big-calendar.css ' 文件?
  • 我想帮助你,但是没有 css 很难理解发生了什么:)
  • 感谢您的评论,我已将 CSS 复制并粘贴到 pastebin:pastebin.com/p3bsYPQS
  • 好的,我会尽力解决你的问题
  • 感谢您的帮助,我认为它与 CSS 无关;但如果我知道我就不会问了!

标签: javascript reactjs react-hooks react-big-calendar


【解决方案1】:

React 不喜欢 mutatiton,因此您的代码会出错。

你需要改变你的功能

  function handleSelect({ start, end }) {
    const title = window.prompt("New Event name");
    if (title) {
      var newEvent = {
        start: start,
        end: end,
        title: title
      };
      setEventsList([...eventsList, newEvent]);
    }
  }

在这个函数中我只改变了这些字符串

let updateEventsList = eventsList;
updateEventsList.push(newEvent);
setEventsList(updateEventsList);

我就是这么做的

setEventsList([...eventsList, newEvent]);

【讨论】:

  • 最好在 react 中使用 concat 或 rest 参数
  • 非常感谢,我花了很长时间来搞乱 useEffect;吠叫完全错误的树。非常感谢。
  • 很高兴能为您提供帮助。如果你有一些问题,你可以在这里写信给我,我会尽力帮助你:) 我喜欢你的项目
猜你喜欢
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多