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

React Native中使用Firebase Realtime Database填充Picker选项问题

问题根因

  • 不可以直接在JSX渲染逻辑中调用异步方法,generateList返回的是Promise对象,无法直接作为React节点渲染
  • 没有使用状态存储从Firebase拉取到的选项数据,异步请求拿到结果后不会触发组件重渲染,Picker无法同步更新选项

修改方案

新增状态存储下拉选项列表,在按钮点击(或页面加载)时触发Firebase数据拉取,拿到数据后更新状态,直接用状态生成Picker选项即可,修改后完整代码如下:

import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Text, Pressable } from 'react-native';
import { Picker } from '@react-native-picker/picker';
import Firebase from './config/firebase';

const Test = () => {
  const [selectedAnimal, setSelectedAnimal] = useState();
  // 新增状态存储下拉选项列表
  const [animalOptions, setAnimalOptions] = useState([]);

  const generateList = (path) => {
    const Listener = Firebase.database().ref(path);
    return Listener.once('value');
  };

  // 如果需要页面加载时自动拉取选项,打开下方useEffect代码即可
  // useEffect(() => {
  //   generateList('/Static/Animals').then(data => {
  //     setAnimalOptions(data.val() || [])
  //   })
  // }, [])
  
  return (
    <View style={styles.container}>
      <View style={styles.InputContainer}>
      <Picker
        selectedValue={selectedAnimal}
        style={styles.UserInput}
        onValueChange={(itemValue) => setSelectedAnimal(itemValue)}
      >
        {/* 遍历状态生成Picker选项 */}
        {animalOptions.map(i => <Picker.Item key={i} label={i.toString()} value={i} />)}
      </Picker>
      </View>
      <Pressable
        style={styles.button}
        android_ripple={{ color: 'white' }}
        onPress={() => {
          generateList('/Static/Animals').then(data => {
            const list = data.val() || []
            console.log(list);
            // 更新状态触发组件重渲染
            setAnimalOptions(list)
          })
        }}
      >
      <Text style={styles.buttoncontent}>Test</Text>
      </Pressable>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    marginHorizontal: 8,
  },
  InputContainer: {
    alignSelf: 'stretch',
    marginBottom: 20,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'darkviolet',
    borderRadius: 4,
  },
  UserInput: {
    fontSize: 16,
    height: 42,
    paddingHorizontal: 8,
  },
  button: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    paddingHorizontal: 32,
    marginVertical: 5,
    borderRadius: 4,
    elevation: 5,
    backgroundColor: 'cornflowerblue',
  },
  buttoncontent: {
    textAlign: 'center',
    fontSize: 16,
    lineHeight: 24,
    fontWeight: 'bold',
    color: 'white',
  },
});

export default Test;

修改后点击Test按钮即可拉取Firebase数据并自动更新Picker选项,无需额外操作。

内容的提问来源于stack exchange,提问作者Niket

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:57:03