Angular中FullCalendar的EventInput数组无法动态添加对象问题
解决FullCalendar中EventInput数组push报错的问题
我来帮你搞定这个问题~你遇到的ERROR TypeError: Cannot read property 'push' of undefined本质原因很简单:你调用push的时候,this.events还没有被初始化为一个数组。虽然你后面有this.events = [...]的赋值操作,但如果这个初始化逻辑在push之后执行,或者某些场景下没被执行到,就会触发这个错误。
下面是几种靠谱的解决方法:
1. 声明时直接初始化空数组
这是最稳妥的方式,在定义events属性的时候就给它一个空数组的初始值,这样不管什么时候调用push,数组都是存在的:
import { EventInput } from '@fullcalendar/core'; // 直接初始化空数组 events: EventInput[] = []; // 之后可以放心push const obj1 = { title: '事件1', allDay: false, start: choosenStartDate, end: choosenEndDate, backgroundColor: RateColor.SpecialRate, borderColor: RateColor.SpecialRate }; this.events.push(obj1);
2. 调用push前先检查并初始化
如果你的events需要在特定时机(比如异步请求后)才初始化,可以在push前加个判断,确保数组存在:
// 添加事件前先确认数组已初始化 if (!this.events) { this.events = []; } this.events.push(obj1); this.events.push(obj2);
3. 循环添加的完整示例
如果要批量循环添加多个事件对象,结合上面的初始化方式,代码可以这样写:
import { EventInput } from '@fullcalendar/core'; events: EventInput[] = []; // 假设你有多个要添加的事件对象 const eventObjects = [ { title: '特殊费率1', allDay: false, start: '2024-05-10', end: '2024-05-11', backgroundColor: RateColor.SpecialRate, borderColor: RateColor.SpecialRate }, { title: '特殊费率2', allDay: false, start: '2024-05-12', end: '2024-05-13', backgroundColor: RateColor.SpecialRate, borderColor: RateColor.SpecialRate }, { title: '常规费率', allDay: false, start: '2024-05-14', end: '2024-05-15', backgroundColor: RateColor.NormalRate, borderColor: RateColor.NormalRate }, ]; // 循环添加到数组 eventObjects.forEach(event => { this.events.push(event); });
额外注意:让FullCalendar更新视图
如果你用的是Angular、React这类框架,仅仅push事件可能不会触发FullCalendar的视图更新(因为框架依赖引用变化来检测变更)。这时候可以通过重新赋值数组的方式触发更新:
// 用扩展运算符创建新数组,替换原数组 this.events = [...this.events, obj1, obj2]; // 循环添加的话可以这样 this.events = [...this.events, ...eventObjects];
这样FullCalendar就能感知到事件数组的变化,自动更新日历视图了。
内容的提问来源于stack exchange,提问作者Kartheek Sarabu
相关产品推荐
相关产品推荐

