将实时 firebase 数据添加到平面列表
Adding Real Time firebase data to a flatlist
当我将数据从我的应用程序发送到我的 firebase 数据库时,它运行良好。我想获取这些数据并将其显示在平面列表中。我尝试了下面描述的方式,但它不会在平面列表中显示任何内容。我怎样才能解决这个问题?
获取数据的代码
const [array,setArray] = useState([])
useEffect(() => {
firebase.database().ref().on('value', (snapshot) =>{
var update = []
snapshot.forEach((child)=>{
update.push({
key: child.key,
posts:child.val().posts
})
})
setArray({array:update}) .// i want to add the array "Update" to the array hook i initialized
})
}, []);
我的平面列表代码
<SafeAreaView style={styles.container1}>
<FlatList
data={array}
keyExtractor={(item)=>item.key}
refreshing={refreshing}
onRefresh={onRefresh}
renderItem={({item}) => (
<TouchableOpacity
style={styles.postText}
onPress={() => navigation.navigate('Details',{newPost: item})}
>
<Text style={styles.item}>{item.posts}</Text>
</TouchableOpacity>
)}
/>
</SafeAreaView>
试试这个方法
问题
从下面的代码中删除 {}
setArray({array:update})
解决方案
setArray(update);
当我将数据从我的应用程序发送到我的 firebase 数据库时,它运行良好。我想获取这些数据并将其显示在平面列表中。我尝试了下面描述的方式,但它不会在平面列表中显示任何内容。我怎样才能解决这个问题?
获取数据的代码
const [array,setArray] = useState([])
useEffect(() => {
firebase.database().ref().on('value', (snapshot) =>{
var update = []
snapshot.forEach((child)=>{
update.push({
key: child.key,
posts:child.val().posts
})
})
setArray({array:update}) .// i want to add the array "Update" to the array hook i initialized
})
}, []);
我的平面列表代码
<SafeAreaView style={styles.container1}>
<FlatList
data={array}
keyExtractor={(item)=>item.key}
refreshing={refreshing}
onRefresh={onRefresh}
renderItem={({item}) => (
<TouchableOpacity
style={styles.postText}
onPress={() => navigation.navigate('Details',{newPost: item})}
>
<Text style={styles.item}>{item.posts}</Text>
</TouchableOpacity>
)}
/>
</SafeAreaView>
试试这个方法
问题
从下面的代码中删除 {}
setArray({array:update})
解决方案
setArray(update);