【问题标题】:Toggle boolean value in Firestore with React App使用 React App 在 Firestore 中切换布尔值
【发布时间】:2026-01-24 00:30:02
【问题描述】:

我目前正在使用 React 和 Firestore 构建一个 TODO 应用程序。 这是我第一次使用 Firestore,我遇到了一个问题。

我已经创建了用于在数据库和 UI 中添加和删除待办事项的函数。 但是,我在尝试切换布尔值“已完成”时遇到了一些困难。 这是我当前为待办事项调用的 onClick 函数。

const todos = firebase.firestore().collection("todos");

markComplete = (id) => {
  todos
   .doc(id)
   .update({ completed: !completed })
   .then(function () {
     console.log("Todo successfully updated!");
  })
  .catch(function (error) {
    // The document probably doesn't exist.
    console.error("Error updating todo: ", error);
  });

似乎我无法以这种方式切换布尔值,因为“!完成”返回未定义。

对我应该如何使用 React + Firestore 切换布尔值有什么建议吗? 我尝试阅读文档但没有成功。

【问题讨论】:

  • 注意:我还尝试通过运行 .get() 函数来分配 currentComplete 的值,这可以让我像这样切换值: update{complete:!currentComplete} 这对我不起作用由于数据库的响应时间。

标签: javascript reactjs firebase google-cloud-firestore desktop-application


【解决方案1】:

您需要先读取文档以获取completed字段的值,然后写入新值。

  markComplete = (id) => {
    todos
      .doc(id)
      .get()
      .then(function (doc) {
        if (doc.exists) {
          return doc.ref.update({ completed: !doc.data().completed });
        } else {
          // Throw an error
        }
      })
      .then(function () {
        console.log('Todo successfully updated!');
      })
      .catch(function (error) {
        // The document probably doesn't exist.
        console.error('Error updating todo: ', error);
      });
  };

【讨论】:

  • 很高兴知道我可以在同一行获取()和更新!
  • 我们其实是chaining the promises,为了背靠背执行两个异步操作(get()update())。