我正在尝试将数据连接到状态为oject的现有数组中。在console.log(data)中,我按预期获取数据,但未与this.state.listData合并在一起。
“ react-native”:“ 0.61.5”, “ @ react-native-firebase / firestore”:“ ^ 6.3.4”,
retrieveMore = async () => {
const { navigation } = this.props;
const title2 = navigation.getParam('title2', null);
userEmail = firebase.auth().currentUser.email;
try {
const data = [];
await database.collection("All Recipes").orderBy("reviewCount", "desc").startAfter(this.state.lastVisible).limit(this.state.limit).get().then(doc => {
doc.forEach( async (doc) =>{
const {filter, id , name, image} = doc.data();
lastVisible = doc;
let recipeId = doc.data().id;
let test = await database.collection("All Recipes").doc(recipeId).collection("Reviews").onSnapshot(function(querySnapshot) {
let data2 = [];
querySnapshot.forEach(function(doc) {
const { Rating } = doc.data();
data2.push({
Rating: Rating,
});
});
const totalRating = data2.reduce((prev,next) => prev + next.Rating,0);
let averageRating = parseInt((Math.round(totalRating/data2.length * 100) / 100).toFixed(1));
let totalReview = Math.abs(data2.length) > 999 ? Math.sign(data2.length)*((Math.abs(data2.length)/1000).toFixed(1)) + 'k' : Math.sign(data2.length)*Math.abs(data2.length);
data.push({
filter: filter,
id:id,
name:name,
image:image,
averageRating: averageRating,
totalReview: totalReview,
});
});
});
console.log(data);
this.setState({
listData:[...this.state.listData, ...data],
lastVisible: lastVisible,
loading: false,
});
})
}
catch (error) {
console.log(error);
}
};
如果我注释了如下代码,则数据和this.state.listData完美地结合在一起,但是没有averageRating和totalReview。
const data = [];
await database.collection("All Recipes").orderBy("reviewCount", "desc").startAfter(this.state.lastVisible).limit(this.state.limit).get().then(doc => {
doc.forEach( async (doc) =>{
const {filter, id , name, image} = doc.data();
lastVisible = doc;
let recipeId = doc.data().id;
// let test = await database.collection("All Recipes").doc(recipeId).collection("Reviews").onSnapshot(function(querySnapshot) {
// let data2 = [];
// querySnapshot.forEach(function(doc) {
// const { Rating } = doc.data();
// data2.push({
// Rating: Rating,
// });
// });
// const totalRating = data2.reduce((prev,next) => prev + next.Rating,0);
// let averageRating = parseInt((Math.round(totalRating/data2.length * 100) / 100).toFixed(1));
// let totalReview = Math.abs(data2.length) > 999 ? Math.sign(data2.length)*((Math.abs(data2.length)/1000).toFixed(1)) + 'k' : Math.sign(data2.length)*Math.abs(data2.length);
data.push({
filter: filter,
id:id,
name:name,
image:image,
// averageRating: averageRating,
// totalReview: totalReview,
});
});
// });
console.log(data);
this.setState({
listData:[...this.state.listData, ...data],
lastVisible: lastVisible,
loading: false,
});
})
答案 0 :(得分:0)
this.setState(state=>({
listData:[...state.listData, ...data],
lastVisible: lastVisible,
loading: false,
}));
尝试一下可能会对您有所帮助