为了账号安全,请及时绑定邮箱和手机立即绑定

Firebase 的数据位置

Firebase 的数据位置

森栏 2023-03-10 16:04:12
我试图保持我从 firebase 获得的数据的位置但是当我刷新页面时它显示在不同的位置而不是他创建的位置我想使用 'position' 和 'beforeend' 但结果是一样的例如我发布 (a,b,c,d,e) 并且当我刷新页面时它显示 (e,d,a,b,c) here some pictures enter image description hereconst addForm = document.querySelector(".add");const list = document.querySelector(".todos");const search = document.querySelector(".search input");// generate new toDo'sconst generateTemplate = (toDo, id) => {  let html = ` <li data-id=${id} class="list-group-item d-flex justify-content-between align-items-center">    <span>${toDo.title}</span><i class="far fa-trash-alt delete"></i>  </li>`;  const position = "beforeend";  list.insertAdjacentHTML(position, html);};const deleteTodo = (id) => {  const todos = document.querySelectorAll("li");  todos.forEach((toDo) => {    if (toDo.getAttribute("data-id") === id) {      toDo.remove();    }  });};// get the info in the pagedb.collection("Todos").onSnapshot((snapshot) => {  snapshot.docChanges().forEach((change) => {    const doc = change.doc;    if (change.type === "added") {      generateTemplate(doc.data(), doc.id);    } else if (change.type === "removed") {      deleteTodo(doc.id);    }  });});// submit the todoaddForm.addEventListener("submit", (e) => {  e.preventDefault();  const now = new Date();  const toDo = {    title: addForm.add.value.trim(),    created_at: firebase.firestore.Timestamp.fromDate(now),  };  db.collection("Todos")    .add(toDo)    .then(() => {      console.log("todo added");    })    .catch((err) => {      console.log(err);    });  addForm.reset();});// delete todo'slist.addEventListener("click", (e) => {  if (e.target.classList.contains("delete")) {    const id = e.target.parentElement.getAttribute("data-id");    db.collection("Todos")      .doc(id)      .delete()      .then(() => {        console.log("Todo Deleted");      });  }});
查看完整描述

1 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

您需要使用orderByfetch documents with sorting。
它应该看起来像这样。

db.collection("Todos")
  .orderBy('created_at')
  .get()
  .then((snapshot) => {
    snapshot.docs.forEach((doc) => console.log(doc.data()));
  });


查看完整回答
反对 回复 2023-03-10
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信