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

React Native中Redux Toolkit对接Firestore无法获取数据如何解决

问题修复方案

你代码里存在3处核心错误,修改后即可正常拿到数据:

  • Firestore调用collection.get()返回的是QuerySnapshot实例,而非直接的文档数组,需要先访问它的docs属性才能拿到可遍历的文档列表
  • 状态字段名不匹配:initialState中定义的存储轮播图数组的字段是imageArray,但你在成功回调中往不存在的userData字段插入数据,导致数据无法写入状态
  • 直接打印原始payload得到的是Firestore快照对象,不是业务层需要的字段数据,会误以为没拿到返回结果

以下是修正后的完整代码:

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import firestore from '@react-native-firebase/firestore';

// 提前在thunk中处理Firestore返回的快照,直接返回业务需要的数组
export const getCarouselImages = createAsyncThunk("/carouselImages", async () => {
  const querySnapshot = await firestore().collection('Users').get();
  return querySnapshot.docs.map(doc => doc.data());
});

const initialState = {
  isLoading: false,
  failed: true,
  success: false,
  imageArray:[],
};

const carouselData = createSlice({
  name: "carouselImageSlice",
  initialState,
  reducers: {
    resetCarouselData: () => initialState,
  },
  extraReducers: (builder) => {
    builder.addCase(getCarouselImages.fulfilled, (state, { payload }) => {
      state.isLoading = false;
      state.failed = false;
      state.success = true;
      // 直接把处理好的数组赋值给对应状态字段
      state.imageArray = payload;
      // 这里打印的就是你需要的业务数据数组
      console.log(payload)
    });
    builder.addCase(getCarouselImages.rejected, (state) => {
      state.isLoading = false;
      state.failed = true;
      state.success = false;
    });
    builder.addCase(getCarouselImages.pending, (state) => {
      state.isLoading = true;
      state.failed = false;
      state.success = false;
    });
  },
});

export const { resetCarouselData } = carouselData.actions;

export default carouselData.reducer;

如果你原来的Users集合存储的不是轮播图数据,把collection('Users')改成你实际存储轮播图的集合名称即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:36:02