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

React.js中如何循环读取Firestore嵌套map数据无需手动指定xp1等字段

数据库结构示意图

实现方案

思路:无需硬编码xp1、xp2等字段名,只需在获取Firestore文档数据后,筛选出所有符合命名规则的xp类字段,整理为数组后存入状态,渲染时直接遍历该数组即可。

1. 修改数据请求逻辑

调整fetchExperience方法,在拿到数据后做字段过滤:

const fetchExperience = async () => {
  try {
    const docs = await firebase
      .collection("portfolioV2")
      .doc("exp")
      .get();
    const data = docs.data();
    // 筛选所有xp前缀的字段,整理为数组
    const xpArr = Object.entries(data)
      // 如需严格匹配xp+数字格式可以替换为下一行代码
      // .filter(([key]) => /^xp\d+$/.test(key))
      .filter(([key]) => key.startsWith('xp'))
      .map(([key, val]) => ({ fieldName: key, ...val }));
    // 如有需要累加历史数据可保留展开写法,否则直接setExperience(xpArr)即可
    setExperience([...Experience, ...xpArr]);
  } catch (err) {
    console.log("Error getting documents", err);
  }
};

2. 修改渲染逻辑

直接遍历处理好的xp数组即可,不需要再指定具体xp字段:

{Experience && Experience.map((xpItem) => {
  return (
    <div className="text-white" key={xpItem.fieldName}>
      <p dangerouslySetInnerHTML={{ __html: xpItem.desc }} />
    </div>
  );
})}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:15:01