首页 > 解决方案 > 结合 limitToFirst() 和 limitToLast() 会导致意外行为

问题描述

我在实时 Firebase 数据库上有以下数据集:

{
    "posts": {
        "key1": {
            message: "message",
            title: "title",
            timeStamp: 1513160947658
        },
        "key2": {
            message: "message",
            title: "title",
            timeStamp: 1625904019915
        },
        "key3": {
            message: "message",
            title: "title",
            timeStamp: 1626171405405
        }
    }
}

这是 Firebase 组件:

Firebase.js

import { get, getDatabase, limitToFirst, limitToLast, onValue, orderByChild, query, ref } from 'firebase/database'
import firebase from 'firebase/compat/app'
import 'firebase/compat/database'

const config = { ... }
const db = getDatabase()

firebase.initializeApp(config)

export { db, get, limitToFirst, limitToLast, onValue, orderByChild, query, ref }

组件获取第一个和最后一个帖子:

FirstAndLast.js

import { db, get, limitToFirst, limitToLast, orderByChild, query, ref } from './Firebase'

const fetch = async () => {

    // If I execute both lines, Listener.js snapshot.val() returns a null value 
    // If I remove one of these lines, Listener.js snapshot.val() returns the desired object
    let snapshotFirst = await get(query(ref(db, 'posts'), orderByChild('timeStamp'), limitToFirst(1)))
    let snapshotLast  = await get(query(ref(db, 'posts'), orderByChild('timeStamp'), limitToLast(1)))

}

另一个组件监听key2分支:

Listener.js

import { db, onValue, ref } from './Firebase'

onValue(ref(db, 'posts/key2'), snapshot => {

    console.log(snapshot.val())

})

如果我同时执行两个组件,Listener.js首先打印所需的对象,但稍后返回一个null值作为最终结果。如果我在 删除(或评论)其中一张快照FirstAndLast.js,则没有任何问题。

组合limitToFirst()和有什么问题limitToLast()吗?

标签: javascriptfirebasefirebase-realtime-database

解决方案


推荐阅读