我一直在努力让这个sveltekit代码在过去的1周内工作,无论我如何尝试,它似乎都不起作用。
在我进入代码之前,这是错误消息:
Cannot read properties of undefined (reading 'length') TypeError: Cannot read properties of undefined (reading 'length')
at Proxy.each (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1710:31)
at eval (/src/lib/components/officer-list.svelte:74:29)
at eval (/src/lib/components/officer-list.svelte:109:5)
at officer-list.svelte:45:12
at Object.$$render (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1745:22)
at eval (/src/lib/sections/training-record.svelte:25:94)
at Object.$$render (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1745:22)
at eval (/src/routes/admin/index.svelte:17:97)
at Object.$$render (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1745:22)
at Object.default (root.svelte:43:39)
这是我的代码从Firebase获取数据:
<script lang="ts" context="module">
// Import Firebase
import { db } from '$lib/scripts/firebaseInit'; //from my custom FirebaseInit.ts
import { collection, getDocs } from 'firebase/firestore';
export async function load() {
let allOfficers = [];
console.log("Loading data");
const querySnapshot = await getDocs(collection(db, "officers"));
// console.log(querySnapshot);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
let data = doc.data();
// console.log(doc.id, " => ", data);
allOfficers.push(data);
});
console.log(allOfficers)
return {
props: { allOfficers }
};
}
</script>
<script lang="ts">
export let allOfficers;
</script>
下面是我渲染数据的代码:
<div class="officer__list">
{#each allOfficers as officer}
<div class="officer__card accordion">
<div class="officer__content-details">
<h4 class="officer-name">{officer.name.displayed}</h4>
<p class="officer-rank-appointment">
Rank 1 | Head of Department
</p>
</div>
</div>
{/each}
</div>
如果你想知道我的FirebaseInit.ts
工作不正常,我有另一个例子,工作不改变任何在脚本标签:
<div class="test-container">
<ul>
{#each allOfficers as officer}
<li>
{officer.name.displayed}
</li>
{/each}
</ul>
</div>
上面的工作就像魔术一样,不改变脚本标签中的任何内容。
编辑:这是一个更大的苗条文件中的组件。我意识到当我把它作为自己的路线时,它会起作用…?怎么了?
所以我已经设法解决了这个问题,我不能使用上下文模块在组件级别加载数据。在我将加载的脚本标记内容移动到路由级别之后,它就可以完美地工作了。我只需要把它作为props传递给各个组件。