Firebase V9获取数据后Redux Dispatch参数变为Undefined问题排查
问题分析与解决
从Firebase V9获取数据后,console.log能正常打印数据,但将数据作为参数dispatch Redux action时,数据变为undefined,添加await也无法解决。
核心原因
在getFeedbacks action中,使用querySnapshot.forEach()赋值feedbacks变量,但**forEach方法没有返回值(默认返回undefined)**,导致最终传递给getFeedbacksSuccess的参数是空值。
解决方案
将forEach替换为map方法(map会遍历并返回新数组,用于收集文档数据),或手动创建数组通过forEach推送数据。同时修正代码中的拼写错误和参数传递问题:
修改后的actions.js
import * as types from './actionTypes' import { db } from '../firebase'; import { collection, getDocs } from "firebase/firestore"; const getFeedbacksStart = () => ({ type: types.GET_FEEDBACKS_START, }); // 修正拼写错误:Sussess → Success const getFeedbacksSuccess = (feedbacks) => ({ type: types.GET_FEEDBACKS_SUCCESS, payload: feedbacks }); // 传递error参数到action const getFeedbacksFail = (error) => ({ type: types.GET_FEEDBACKS_FAIL, payload: error }); export const getFeedbacks = () => { return async function (dispatch) { dispatch(getFeedbacksStart()); try { const querySnapshot = await getDocs(collection(db, "feedbacks")); querySnapshot.forEach((doc) => { console.log(doc.id, " => ", doc.data()) }); // 用map遍历收集所有文档数据,可选保留文档ID const feedbacks = querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() })); dispatch(getFeedbacksSuccess(feedbacks)) } catch (error) { dispatch(getFeedbacksFail(error)) } } }
补充优化:调整reducer初始状态
由于获取的是列表数据,将初始状态中的feedbacks从对象改为数组更合理:
import * as types from './actionTypes' const initialState = { feedbacks: [], // 改为数组 loading: false, error: null, }; const feedbackReducer = (state = initialState, action) => { switch (action.type) { case types.GET_FEEDBACKS_START: return { ...state, loading: true } case types.GET_FEEDBACKS_SUCCESS: return { ...state, loading: false, feedbacks: action.payload, } case types.GET_FEEDBACKS_FAIL: return { ...state, loading: false, error: action.payload, } default: return state; } } export default feedbackReducer;
内容的提问来源于stack exchange,提问作者lsokol
相关产品推荐
相关产品推荐

