小编Ren*_*lic的帖子

如何监听 Firebase 中的特定值变化?

我的数据结构如下:compliments/received/{uid}/{complimentId} 在此输入图像描述

我想听听有关恭维/已收到/{uid}/{complimentId}/updatedAt 的更改

我的代码是:

firebase.database().ref('compliments/received/' + currentUser._id).on('child_changed', (snap) => {
  console.log('update in action', snap.val())
  snap.ref.child('updatedAt').on('value', () => onUpdate(snap))
});
Run Code Online (Sandbox Code Playgroud)

问题:当我更新给定数据库路径上的任何字段时,此侦听器会触发,例如:当我将“seen”从 0 设置为 1 时。我想仅在 UpdatedAt 字段的值更改时触发此侦听器。

到目前为止我尝试过的:

firebase.database().ref('compliments/received/' + currentUser._id).on('child_changed', (snap) => {
  console.log('update in action', snap.val())
  snap.ref.child('updatedAt').on('child_changed', () => onUpdate(snap))
});
Run Code Online (Sandbox Code Playgroud)

当我更改 UpdatedAt 字段的值时,此侦听器不会触发。

有什么建议欢迎留言!谢谢!

根据阿里的回答解决方案:

firebase.database().ref('compliments/received/' + currentUser._id).on('child_added', (snap) => {
    console.log('add in action', snap.val());
    firebase.database().ref('compliments/received/' + currentUser._id)
    .child(snap.key).child('updatedAt').on('value', async () => {
      const newSnap = await firebase.database().ref('compliments/received/' + currentUser._id)
      .child(snap.key).once('value')
      onUpdate(newSnap)
    })
});
Run Code Online (Sandbox Code Playgroud)

javascript firebase firebase-realtime-database

5
推荐指数
1
解决办法
4288
查看次数