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

React Native中如何将Firestore数据转换为数组(Redux场景)

解决Firestore数据转数组并在Redux中随机切换的问题

1. 将Firestore键值对转换为对象数组

Firestore返回的键值对对象,可通过Object.entries()拆解为键值数组,再映射成你需要的结构:

// 基于action.payload(Firestore返回的数据)转换数组
const dataArray = Object.entries(action.payload).map(([key, text]) => ({
  key,
  text
}));

转换后dataArray的结构如下:

[
  { key: "ref1", text: "trying text 1" },
  { key: "ref2", text: "trying text 2" },
  { key: "ref3", text: "trying text 3" },
  { key: "ref5", text: "trying text 5" }
]

2. 在Redux Reducer中实现随机切换逻辑

修改你的slice代码,在shuffleMild里完成数组转换、随机选取元素并更新state:

export const mildvalue = createSlice({
  name: "mild",
  initialState: { text: "Press to refresh", key: 1 },
  reducers: {
    shuffleMild: (state, action) => {
      // 转换Firestore数据为目标数组
      const dataArray = Object.entries(action.payload).map(([key, text]) => ({
        key,
        text
      }));

      // 空数组容错,避免索引错误
      if (dataArray.length === 0) return;

      // 随机选取一个元素
      const randomIndex = Math.floor(Math.random() * dataArray.length);
      const randomItem = dataArray[randomIndex];

      // 更新state
      state.text = randomItem.text;
      state.key = randomItem.key;
    }
  }
});

3. 额外提示

  • 若需要组件初始化时就加载数据并随机显示,可在组件的useEffect中调用该action,传入Firestore获取到的数据。
  • 保留空数组判断,防止Firestore返回空对象时出现报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:06:18