orderByKey不是reactjs expo中的函数?

mdfafbf1  于 2023-02-22  发布在  React
关注(0)|答案(1)|浏览(84)

我尝试随机化firebase实时数据库选择的节点,但我只能让它随机化美食,而不是美食+商店
当前代码为:它只能随机选择菜肴,但对于它正在获得的商店,它在我的控制台中是空的[]

import { StyleSheet, Text, View } from 'react-native'

import {db} from '../firebase'
import React, {useEffect, useState} from 'react'
import {ref, get} from 'firebase/database'

const SubScreen2 = () => {
  
  
  
  const [todoData, setToDoData] = useState([])
  
  
  useEffect (() => {
    get(ref(db, "food/Total")).then(snapshot => {
      const count = snapshot.val();
      const random = Math.floor((Math.random() * count));
      return get(ref(db, `food/`).orderByKey().limitToFirst(random + 1))
    }).then(snapshot => {
      const randomKey = Object.keys(snapshot.val())[random];
      setToDoData(snapshot.val()[randomKey]);
    }).catch(error => {
      console.log(error);
    })
  }, [])
  console.log(todoData)
  return (
    <View style={styles.container}>
      {todoData ? (
        <View>
          <Text>{todoData.Description}</Text>
          <Text>{todoData.Location}</Text>
          <Text>{todoData.Halal}</Text>
          <Text>{todoData.OH}</Text>
        </View>
      ) : (
        <Text>Loading...</Text>
      )}
    </View>
  )
}

export default SubScreen2

下面是我的控制台日志,显示了随机选择的菜肴和错误:

我的数据库的一部分:

{
  "food": {
    "Bakery": {
      "Bakery Cuisine": {
        "Description": "Within North Spine Plaza",
        "Halal": "Yes",
        "Location": "50 Nanyang Ave, #01-20 North Spine Plaza, Singapore 639798",
        "OH": "Mon - Sat : 8 AM to 7 PM, Sun Closed"
      }
    },
    "Beverage": {
      "Beverage": {
        "Description": "Within the South Spine food court",
        "Halal": "No",
        "Location": "21 Nanyang Link, Singapore 637371",
        "OH": "Mon - Fri: 7 30 am to 8 pm, Sat - Sun/PH Closed"
      },
      "Beverages": {
        "Description": "Within North Spine Koufu",
        "Halal": "No",
        "Location": "76 Nanyang Dr, #02-03 North Spine Plaza, Singapore 637331",
        "OH": "Mon - Fri : 7 am to 8 pm, Sat : 7 am to 3 pm, Sun Closed"
      },
      "Boost": {
        "Description": "Within North Spine Plaza",
        "Halal": "No",
        "Location": "50 Nanyang Ave, #01-11 North Spine Plaza, Singapore 639798",
        "OH": "Mon - Fri : 10 am to 9 pm, Sat - Sun: 10 am to 6 pm"
      },
      
    "Total": 120,
f4t66c6m

f4t66c6m1#

看起来您混合了V8和V9语法。
更新导入

import {ref, get, query, orderByKey, limitToFirst} from 'firebase/database'

然后使用查询类进行排序、过滤等。

return get(query(ref(db, 'food/'), orderByKey(), limitToFirst(random + 1)));

文件:www.example.comhttps://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data

相关问题