【问题标题】:Get images from Firebase Firestore and add them to an "li"从 Firebase Firestore 获取图像并将它们添加到“li”
【发布时间】:2020-10-14 19:00:20
【问题描述】:

我尝试从 Firebase 存储中检索图像,然后将它们添加到作为帖子的“li”标签中。但是在运行下面的代码时我得到了 src=undefined 。 “li”标签中的 div 有效。谁能帮帮我?

为什么会出现错误:无法读取未定义的属性“get”?

HTML:

<div class="container">
   <ul class="posts">
   </ul>
</div>

JavaScript:

var postDocRef = db.collection('posts').doc(uid).collection('userPosts')

postDocRef.get().then(snapshot => {
setupPosts(snapshot.docs)
})

const posts = document.querySelector('.posts');

const setupPosts = (data) => {

    let html = '';
    data.forEach(doc => {

        var docRefIDpost = docRef.id

        const post = doc.data();
        const li = `
        <li>
            <div class="title">${post.title}</div>
            <div class="content">${post.content}</div>
            <img class="img">
        </li>
        `;

        var imgRef = db.collection("posts").doc(uid).collection('userPosts').doc(docRefIDpost);

        imgRef.get().then(function(snapshot) {
            var picURL = snapshot.get("picURL")
            
                    var imgpost = document.querySelector(".img");
        
                    imgpost.src = picURL
        
            })

        


        html += li
    })

    posts.innerHTML = html;

}
});

【问题讨论】:

    标签: javascript html firebase google-cloud-firestore google-cloud-storage


    【解决方案1】:

    每个userPosts 文档的结构如何?你检查过imgRefsnapshot不为空吗? 我相信实际的问题可能是您在访问imageURL 时错过了对data() 的调用:

    var picURL = snapshot.data().picURL
    

    【讨论】:

    • 仍然没有变化。但是现在,我在控制台中收到一个错误:无法读取未定义的属性“get”。快照不为空,因为我在控制台中记录了快照。
    • 我猜是 .get() 函数出了问题。
    • 是的,是get()函数的问题。data()返回的对象是js对象——可以直接访问picURL等属性。我已经调整了上面的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多