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

在NextJS 13中如何从Firestore文档获取并使用文档ID?

解决方案

你只需要在构建customerData数组时,把文档ID和数据一起存入即可,不用单独只存data()。有两种简单的实现方式:

方式一:用map直接生成目标数组(更简洁)

把你原来的forEach替换成map,直接返回包含id和数据的对象:

async function getCustomers() {
  const customers = await getDocs(collection(FIREBASE_FIRESTORE, "client"));
  return customers;
}

export default async function CustomersPage() {
  const customers = await getCustomers();
  // 直接用map生成包含id的数组
  const customerData = customers.docs.map(doc => ({
    id: doc.id,
    ...doc.data()
  }));

  return (
    <div>
      {customerData.map((customer) => {
        return (
          // 这里就能直接用customer.id了,比如:
          <div key={customer.id}>
            <p>ID: {customer.id}</p>
            <p>名称: {customer.name}</p>
            {/* 其他字段 */}
          </div>
        );
      })}
    </div>
  );
}

方式二:修改原forEach逻辑

如果你更习惯用forEach,可以在push的时候把id也加进去:

export default async function CustomersPage() {
  const customers = await getCustomers();
  const customerData = [];

  customers.docs.forEach((doc) => {
    customerData.push({
      id: doc.id,
      ...doc.data()
    });
  });

  return (
    <div>
      {customerData.map((customer) => {
        return (
          // 同样可以访问customer.id
          <div key={customer.id}>
            {/* 你的元素内容 */}
          </div>
        );
      })}
    </div>
  );
}

注意点

  • 循环渲染React元素时,一定要给每个元素加上唯一的key属性,这里用文档IDcustomer.id是最合适的选择,符合React的性能优化要求。
  • 你之前的代码里漏写了return语句包裹JSX部分,这也是需要修正的地方,否则页面不会渲染内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:53:11