首页 > 解决方案 > 使用单个 Firestore 文档中的字段更新 DOM

问题描述

我正在尝试将列表呈现给 DOM,然后根据单个 Firestore 文档的快照更新列表元素。

在收听集合快照并使用 onChange() 函数时,我已经能够轻松完成此操作,但是,在收听单个文档快照时,此函数不可用。

我以为我已经用以下代码解决了这个问题:

const detailList = document.querySelector('#detail-list');

function loadDetail(){

// Render DOM
let name = document.createElement('li');
let description = document.createElement('li');
name.textContent = 'loading...'
description.textContent = 'loading...'
name.setAttribute('id', 'name');
description.setAttribute('id', 'description');
detailList.appendChild(name);
detailList.appendChild(description);


// Listen for document snapshot and update DOM
db.collection('1003')
.doc(localStorage.getItem('headingID'))
.collection('items')
.doc(localStorage.getItem('itemID'))
.onSnapshot(doc => {
    document.getElementById('name').innerHTML = doc.data().name;
    document.getElementById('description').innerHTML = doc.data().description;

})
}

但是,运行时会抛出以下错误:

app.js:194 Uncaught TypeError: Cannot read property 'name' of undefined
    at Object.db.collection.doc.collection.doc.onSnapshot.doc [as next] (app.js:194)
    at next (firebase.js:1)
    at firebase.js:1

我不确定为什么这不能按预期工作。

标签: javascripthtmlfirebasegoogle-cloud-firestore

解决方案


推荐阅读