[英]react native add data dynamically to Picker
I'm using react-native picker.我正在使用 react-native 选择器。
I want to get data from firebase and insert it dynamically to the Picker.我想从 firebase 获取数据并将其动态插入到 Picker 中。
the request from the firebase is asynchronous, so I want to use it to my favor.来自 firebase 的请求是异步的,所以我想使用它对我有利。
I have a function that getting the data from the firebase and then returning HTML content with the data to the picker.我有一个 function 从 firebase 获取数据,然后将 HTML 内容与数据一起返回给选择器。
the problem is that the getUsers() function returning at first empty array and after 2 seconds it returning the full data that I was expecting.问题是 getUsers() function 首先返回空数组,然后在 2 秒后返回我期望的完整数据。
but the picker already rendered with an empty array.但是选择器已经用一个空数组渲染了。
how I insert the data to the picker in run time?如何在运行时将数据插入选择器?
I don't want to use ".then" or promise, I want the picker will add item each time the firebase sending one.我不想使用“.then”或 promise,我希望每次 firebase 发送一个时,选择器都会添加项目。
this is the code that getting the data from the firebase这是从 firebase 获取数据的代码
getUsers(){
var items = []
firebase.database().ref().child("Users").on('value',function(snapshot) {
snapshot.forEach(function(childData) {
items.push(<Picker.Item key ={childData.val().FullName} value={childData.val().FullName} label={childData.val().FullName} />)
})
}).
return items
}
and this is the picker code这是选择器代码
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<Picker
selectedValue={this.state.PickerValueHolder}
onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >
{this.getUsers()}
</Picker>
</View>
);
}
}
You can add your data (items) on component state and then you can render it from the state.您可以在组件 state 上添加数据(项目),然后您可以从 state 渲染它。
getUsers(){
var items = []
firebase.database().ref().child("Users").on('value',function(snapshot) {
snapshot.forEach(function(childData) {
usersToShow.push(dta)
items.push(<Picker.Item key ={childData.val().FullName} value={childData.val().FullName} label={childData.val().FullName} />)
})
this.setState({users:items})
}
)
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<Picker
selectedValue={this.state.PickerValueHolder}
onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >
{this.state.users}
</Picker>
</View>
);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.