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

如何在Svelte中显示Firestore所有条目?待办应用UI问题排查

解决Svelte中Firestore数据无法全部展示的问题

问题根源

  1. 你用单个变量msg存储数据,forEach循环中每次赋值都会覆盖之前的值,导致UI仅显示最后一条数据。
  2. querySnapshot是onMount函数内部的局部变量,模板无法访问到它,所以使用{#each querySnapshot as doc}会提示未定义。

修复方案

将存储数据的变量改为数组,在获取Firestore数据时把所有条目存入数组,再通过{#each}遍历数组渲染UI:

修改后的逻辑代码

import { onMount } from 'svelte';
import { addDoc, collection, getDocs } from 'firebase/firestore';
import { db } from './firebase.js'; // 确保你的Firebase初始化路径正确

let items = []; // 改为数组存储所有条目
let textinput = '';

async function f() {
  try {
    const docRef = await addDoc(collection(db, "users"), {
      name: textinput,
    });
    console.log("Document written with ID: ", docRef.id);
    // 添加数据后重新获取列表,更新UI
    const querySnapshot = await getDocs(collection(db, "users"));
    items = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
  } catch (e) {
    console.error("Error adding document: ", e);
  }
}

onMount(async () => {
  const querySnapshot = await getDocs(collection(db, "users"));
  // 将所有文档数据转换为数组,包含id和数据内容
  items = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
});

修改后的模板代码

<h1>
  this is for database
</h1>
<input type="text" bind:value={textinput}>
<button on:click={f}>添加</button> <!-- 建议添加按钮触发添加操作 -->

<!-- 遍历数组渲染所有条目 -->
{#each items as item}
  <p>{item.name}</p>
{/each}

关键改动说明

  • 用数组items替代单个变量msg,存储所有Firestore返回的文档数据。
  • 使用querySnapshot.docs.map()将文档集合转换为数组,每个元素包含文档ID和数据,方便后续操作(比如删除、修改)。
  • 在添加新数据后重新获取列表,确保UI实时更新。
  • 模板中通过{#each items as item}遍历数组,展示所有条目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:05:21