如何在React Native中呈现来自Firestore数据库的数据?
下面是我的代码,该代码仅将数据推送到数组中,但我不知道如何在Card中使用它。我尝试使用Flatlist但失败了。
到目前为止,每当我尝试在控制台中打印数据时,它看起来都像这样:
数组[ “ VD GOT嫉妒”, “样本内容”, ]
我希望该数组在Card或Text组件中呈现
state = {
content: []
}
componentWillMount(){
/* similar to mounted in vue */
this.retrieveAnnouncement()
}
retrieveAnnouncement = () => {
/* retrieve announcements */
firebase.firestore().collection("announcement").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.state.content.push(doc.data().CONTENT);
}).catch(err => console.log(err));
});
};
render() {
return (
<View>
<Button onPress={this.samplePrint} title="Print"></Button>
</View>
)
}
答案 0 :(得分:1)
您可以更改Firebase代码:
retrieveAnnouncement = () => {
const announcements = [];
/* retrieve announcements */
firebase
.firestore()
.collection('announcement')
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
announcements.push(doc.data().CONTENT);
});
this.setState({ content: announcements });// this will set announcements and triger render.
})
.catch(err => console.log(err));
}
在此渲染方法之后,您可以使用内容数组。
render (){
console.log (this.state.content);
const listItems = this.state.content.map((data) => {
return (
<View><Text>{data}</Text></View>
)
})
return (
<View>
<Button onPress={this.samplePrint} title="Print"></Button>
{listItems}
</View>
)
}
希望这将有助于解决您的问题。
答案 1 :(得分:0)
componentWillMount(){
/* similar to mounted in vue */
this.retrieveAnnouncement();
}
retrieveAnnouncement = () => {
const announcements = [];
/* retrieve announcements */
firebase.firestore().collection("announcement").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
announcements.push(doc.data().CONTENT);
}).catch(err => console.log(err));
});
this.setState({content: announcements});
};
render() {
return (
<View>
<Button onPress={this.samplePrint} title="Print"></Button>
<Text>{this.state.content}</Text>
</View>
)
}
答案 2 :(得分:0)
state = {
content: []
}
componentWillMount(){
/* similar to mounted in vue */
this.retrieveAnnouncement()
}
retrieveAnnouncement = () => {
/* retrieve announcements */
let sampleData = firebase.firestore().collection("announcement").get()
.then((querySnapshot) => {
if (querySnapshot.exists) {
return { success: true, data: doc.data() }
} else {
return { success: false, message: "Not Found" }
}
}).catch(error => {
return { success: false, message: error}
});
return sampleData
};
render() {
return (
<View>
<Button onPress={this.samplePrint} title="Print"></Button>
</View>
)
}
确保在每种情况下都添加退货 希望这行得通