javascript - 使用单个 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
我不确定为什么这不能按预期工作。
解决方案
推荐阅读
- neural-network - Pytorch中特定层参数的梯度
- python - 在 matplotlib 中悬停时显示 x 轴的值
- github-pages - NuxtJS 和 Github 用户页面
- vba - 在 VBA 中尝试在多个工作表中创建具有多个条件的动态 Sumifs 公式
- vue.js - 在 vue 2 应用程序中使用 vee-validate 2 和 composition-api
- html - 如何使我的 img:hover 代码与两个不同的代码一起使用?
- json - 使用 ajax 更新 Chart.js 数据
- python - 如何根据python和sqlalchemy中的表数据和关系动态过滤结果?
- c# - 使用 Dapper 添加搜索功能
- python - 使用 Python 初始化和自定义 QML 组件