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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:10:47