繁体   English   中英

仅更新 Firebase v9 实时数据库中的特定数据

[英]Update only specific data in Realtime database of Firebase v9

我是 firebase 并使用 ReactJs 的新手,我想知道如何更新实时数据库中的特定数据,我想将其值更改为 true 或 false 可互换。

图片

这是我的代码。

  const [status, setStatus] = useState(false);
  const [tempId, setTempId] = useState("");
  const [todo, setTodo] = useState("");
  
  const updateStatus = () => {
    update(ref(db, `/${auth.currentUser.uid}/${tempId}`), {
      completed: setStatus(!status),
      todo: todo,
      id: tempId,
    });
  };

先感谢您。

如果您只想更新 status 属性,您可以执行以下操作:

update(ref(db, `/${auth.currentUser.uid}/${tempId}`), {
  completed: !status
});

由于您调用update ,它将使节点的其他属性保持不变。


或者,您可以执行以下操作:

update(ref(db, `/${auth.currentUser.uid}/${tempId}/status`), !status)

或者:

set(ref(db, `/${auth.currentUser.uid}/${tempId}/status`), !status)

这两个都只写入status属性的完整路径。


你会注意到我没有在上面的代码中调用setStatus 相反,我建议您监听状态节点的值,然后在收到回调时调用setStatus

onValue(ref(db, `/${auth.currentUser.uid}/${tempId}/status`), (snapshot) => {
  setStatus(snapshot.val());
});

像这样分离读写操作称为命令查询职责分离(或 CQRS) ,在 Firebase 的情况下,用户甚至不会变慢,因为本地 SDK 会在您调用set或时立即调用onValue处理程序在该路径上update

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM