React Context问题:为何notifications属性初始值始终为undefined,其余正常?
React Context中notifications初始值为undefined的解决方法
问题根源:语法错误
你的代码里useReducer的初始状态对象存在语法错误——test: "test"后面多了一个多余的逗号,导致JavaScript无法正确解析初始状态对象,进而使得notifications的初始值变成undefined。
修正步骤
- 移除初始状态对象末尾的多余逗号:
const [state, dispatch] = useReducer(reducer, {notifications: [], test: "test"})
- 额外检查API返回结构
在fetch_notifications的reducer分支中,你使用了action.payload.messages来更新notifications。如果API.fetchNotifications()返回的对象中没有messages字段,也会导致notifications被设置为undefined。请确认接口返回的数据结构是否符合预期,比如返回的应该是类似{ messages: [...] }的格式。
修正后的完整代码示例
const NotificationContext = createContext(); const reducer = (state, action) => { switch (action.type) { case 'fetch_notifications': return { ...state, notifications: action.payload.messages } case 'try': return { ...state, test: action.payload } default: return state; } }; export const NotificationsProvider = ({children}) => { // 移除了初始状态对象末尾的多余逗号 const [state, dispatch] = useReducer(reducer, {notifications: [], test: "test"}) const tryme = () => { dispatch({type: 'try', payload: "tryingme"}) } const fetchNotifications = async () => { const notifications = await API.fetchNotifications(); dispatch({type: 'fetch_notifications', payload: notifications}) }; return ( <NotificationContext.Provider value={{ state, fetchNotifications, tryme }} > {children} </NotificationContext.Provider> ) }
内容的提问来源于stack exchange,提问作者user6377312
相关产品推荐
相关产品推荐

