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

如何从Firebase实时数据库获取商家列表后随机展示单个商家?

实现随机展示单个商家的修改方案

当然可以实现随机展示单个商家,你可以通过以下步骤修改现有代码:

  1. 新增状态变量存储随机选中的商家
  2. 获取商家列表后随机挑选一个商家
  3. 修改渲染逻辑,只展示选中的随机商家

修改后的完整代码

import { StyleSheet, Text, View } from 'react-native'
import {db} from '../firebase'
import React, {useEffect, useState} from 'react'
import {ref, onValue} from 'firebase/database'

const SubScreen2 = ({route}) => {
  const paramKey = route.params.paramKey
  
  const [todoData, setToDoData] = useState([])
  // 新增状态存储随机选中的商家
  const [randomShop, setRandomShop] = useState(null)
  
  useEffect (() => {
    const starCountRef = ref(db, "food/" + paramKey);
    onValue(starCountRef, (snapshot) =>{
      const data = snapshot.val();
      const newPosts = Object.keys(data).map(key =>({
        id:key,
        ...data[key]
      }));
      setToDoData(newPosts);
      
      // 获取列表后随机挑选一个商家
      if (newPosts.length > 0) {
        const randomIndex = Math.floor(Math.random() * newPosts.length);
        setRandomShop(newPosts[randomIndex]);
      }
    })
  }, [paramKey]) // 添加paramKey到依赖,确保参数变化时重新获取数据
  
  return (
    <View style = {styles.container}>
      {/* 只渲染随机选中的商家 */}
      {randomShop && (
        <View>
          <Text style = {styles.header}>{randomShop.id}</Text>
          {/* 若商家有名称等其他字段,可在这里补充展示,比如 {randomShop.name} */}
        </View>
      )}
    </View>
  )
}

export default SubScreen2

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  header: {
    fontSize: 20,
    fontWeight: 'bold'
  }
})

修改说明

  • 新增randomShop状态变量,专门保存随机选中的商家对象
  • 在数据库回调中,通过Math.floor(Math.random() * 列表长度)生成随机索引,选中对应商家并更新状态
  • 渲染部分不再遍历整个商家列表,只展示randomShop的内容
  • 给useEffect添加paramKey依赖,确保切换菜系参数时能重新获取数据并随机选择

可选:添加"重新随机"功能

如果需要支持点击切换随机商家,可以新增按钮逻辑:

// 先导入TouchableOpacity组件
import { TouchableOpacity } from 'react-native';

// 在组件内添加随机选择函数
const pickRandomShop = () => {
  if (todoData.length > 0) {
    const randomIndex = Math.floor(Math.random() * todoData.length);
    setRandomShop(todoData[randomIndex]);
  }
}

// 在渲染部分添加按钮
{randomShop && (
  <>
    <View>
      <Text style = {styles.header}>{randomShop.id}</Text>
    </View>
    <TouchableOpacity 
      onPress={pickRandomShop} 
      style={{marginTop: 20, padding: 10, backgroundColor: '#eee', borderRadius: 5}}
    >
      <Text>换一个商家</Text>
    </TouchableOpacity>
  </>
)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:45:11