You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo中Firebase实时数据库随机选店及orderByKey报错问题

问题分析与解决方案

问题1:orderByKey is not a function错误

原因:Firebase Realtime Database v9采用模块化API,orderByKey等查询方法不再是ref对象的链式方法,需通过query()函数结合使用。

问题2:无法同时选中菜系+店铺、store数据为空

原因:

  1. 原逻辑仅随机获取了菜系节点,未深入到菜系下的店铺层级
  2. 随机索引基于总店铺数生成,但实际操作的是菜系列表,导致索引越界
  3. 数据库中Total节点位置错误,导致初始count获取失败

完整修正代码

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(null)
  
  useEffect(() => {
    // 第一步:获取所有菜系并随机选择
    get(ref(db, "food")).then(snapshot => {
      const foodData = snapshot.val();
      // 过滤掉Total节点,提取有效菜系
      const cuisines = Object.keys(foodData).filter(key => key !== 'Total');
      if (cuisines.length === 0) throw new Error('没有找到菜系数据');
      
      const randomCuisineIdx = Math.floor(Math.random() * cuisines.length);
      const targetCuisine = cuisines[randomCuisineIdx];
      
      // 第二步:获取选中菜系下的所有店铺
      return get(ref(db, `food/${targetCuisine}`));
    }).then(snapshot => {
      const cuisineData = snapshot.val();
      // 过滤掉Total节点,提取有效店铺
      const stores = Object.keys(cuisineData).filter(key => key !== 'Total');
      if (stores.length === 0) throw new Error('该菜系下没有店铺数据');
      
      const randomStoreIdx = Math.floor(Math.random() * stores.length);
      const targetStore = stores[randomStoreIdx];
      
      // 设置最终店铺数据
      setToDoData(cuisineData[targetStore]);
    }).catch(error => {
      console.error('获取随机店铺失败:', error);
    })
  }, [])

  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>加载中...</Text>
      )}
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  }
})

export default SubScreen2

推荐数据库结构调整

将Total节点移至food根目录(用于统计总店铺数),避免干扰菜系/店铺节点的获取:

{
  "food": {
    "Total": 120,
    "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"
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者L.Calvin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:56:36