You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React日历应用中activeEvent为何返回undefined?

问题分析与解决方案

核心原因:Redux状态取值路径错误

你在useCalendarStore中获取activeEvent的路径完全错误,导致函数内的activeEvent始终是undefined,但Redux DevTools能正确显示状态——因为onSetActiveEvent reducer是正确更新到state.calendar.activeEvent的。

看你的calendarSlice初始状态:

initialState: {
  events: {},
  activeEvent: null,
  isLoadingEvents: true,
},

activeEvent是state.calendar的直接属性,而非state.calendar.events的子属性。但你当前的代码是从state.calendar.events里解构activeEvent:

const { events, activeEvent } = useSelector((state) => state.calendar.events);

events是一个对象,里面根本没有activeEvent字段,所以这里拿到的activeEvent必然是undefined。


修复步骤

  1. 修正useSelector的取值逻辑
    把上面的代码改成直接从state.calendar解构:
const { events, activeEvent } = useSelector((state) => state.calendar);
  1. 额外潜在问题修复(可选但建议)
  • 你的onDeleteEvent reducer中用event._id !== state.activeEvent._id过滤事件,但在startLoadingEvents中,你给事件赋值的是id: doc.id而非_id,这会导致删除逻辑失效,建议统一字段名(比如都用id):
    // onDeleteEvent reducer修改为
    state.events[state.activeEvent.calendarId] = state.events[state.activeEvent.calendarId]
      .filter((event) => event.id !== state.activeEvent.id);
    
  • startSavingEvent中新增事件时,dispatch(onAddEvent)的参数错误,你传的是events局部变量,应该传刚创建的事件对象:
    // 替换原来的dispatch行
    dispatch(onAddEvent({ 
      calendarId: nombre, 
      event: { id: docRef.id, ...calendarEvent, _id: new Date().getTime() } 
    }));
    

验证

修改后,deleteEvent函数中的activeEvent就能正确获取到Redux中存储的活跃事件,console.log也会输出正确的值。

内容的提问来源于stack exchange,提问作者guido

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:07:38