我正在尝试使用 Firebase 实时数据库来填充选择器 ( @react-native-picker/picker
) 中的项目并且反复失败。
我还在下面附上了一个最小的可重现示例。
通过onPress
事件,console.log()
正在打印正确的数组,但我无法使用它生成一个数组供 Picker 使用。
我将非常感谢您提供的任何帮助或资源。
import React, { useState } 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();
var generateList = (path) => {
var Listener = Firebase.database().ref(path);
return Listener.once('value');
};
let pickerGenerator = (dblist) => dblist.map(i => {
return <Picker.Item key={i} label={i.toString()} value={i} />
});
return (
<View style={styles.container}>
<View style={styles.InputContainer}>
<Picker
selectedValue={selectedAnimal}
style={styles.UserInput}
onValueChange={(itemValue, itemIndex) =>
setSelectedAnimal(itemValue)
}>
{/* {generateList('/Static/Animals').then(data => {
pickerGenerator(data.val());
})} */}
</Picker>
</View>
<Pressable
style={styles.button}
android_ripple={{ color: 'white' }}
onPress={() => {
generateList('/Static/Animals').then(data => {
console.log(data.val());
})
}}>
<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;