如何在switch外声明events避免reducer中未定义错误?
解决Reducer中词法作用域与
Cannot read property 'events' of undefined错误 你的问题根源很明确:不是所有触发这个reducer的action都会携带action.data属性,你在switch语句外直接解构action.data,当遇到没有data的action时,就会抛出"无法读取undefined的events属性"的错误。
下面给你两种可行的解决方案:
方案1:给解构设置默认值,避免action.data不存在的情况
你可以在解构的时候给action.data设置一个空对象作为默认值,这样即使action没有data属性,解构也不会报错,只是得到空的events和day对象:
export function eventsForMonth(state = {}, action) { // 给action.data设置默认空对象,避免解构失败 const { events = {}, day = {} } = action.data || {}; const newItems = {}; switch (action.type) { case "EVENTS_MONTH": Object.keys(events).map(event => { newItems[event] = [...events[event].dots]; }); for (let i = -15; i < 85; i++) { const time = day.timestamp + i * 24 * 60 * 60 * 1000; const strTime = timeToString(time); if (!newItems[strTime]) { newItems[strTime] = []; } } return { ...newItems }; case "EVENTS_CALENDAR_MONTH": // ...你的其他代码 default: // 不要忘记default case,返回原state return state; } }
方案2:将解构移到需要用到的case内部(更推荐)
因为只有EVENTS_MONTH这个case才需要用到events和day,把解构放到对应的case里更合理,避免在不需要这些数据的action执行时做无用的解构:
export function eventsForMonth(state = {}, action) { switch (action.type) { case "EVENTS_MONTH": // 仅在需要的case内解构,同时给action.data设置默认值 const { events = {}, day = {} } = action.data || {}; const newItems = {}; Object.keys(events).map(event => { newItems[event] = [...events[event].dots]; }); for (let i = -15; i < 85; i++) { const time = day.timestamp + i * 24 * 60 * 60 * 1000; const strTime = timeToString(time); if (!newItems[strTime]) { newItems[strTime] = []; } } return { ...newItems }; case "EVENTS_CALENDAR_MONTH": // ...你的其他代码 default: return state; } }
另外还要注意:reducer必须要有default case,返回原state,这是Redux reducer的基本规范,避免未匹配到action类型时返回undefined。
内容的提问来源于stack exchange,提问作者Bomber
相关产品推荐
相关产品推荐

