我具有以下功能:
public GetExercisePosts(user: User): ExercisePost[] {
const exercisePosts = new Array<ExercisePost>();
firebase.firestore().collection('exercise-posts').where('created-by', '==', user.Id).onSnapshot((results) => {
results.forEach((postDoc) => {
const exercisePost = Deserializer.DeserializeExercisePost(postDoc);
if (exercisePost) {
exercisePosts.push(exercisePost);
}
});
});
return exercisePosts;
}
另一个React组件将其称为:
public async componentDidMount() {
const personalExercisePosts = this.exerciseService.GetExercisePosts(this.state.currentUser);
this.setState({ personalExercisePosts });
}
这是第一次效果很好,但是一旦快照变化,GetExercisePosts
的原始方法就不会被触发,这是有道理的,因为componentDidMount
仅在组件的生命周期中被调用一次。但是,我确实知道快照函数被称为,因为当我通过Firestore Admin Console添加记录时,它会记录新数据。
如何观察对该快照的变化?或者,该快照会散发出组件可以收听的更改?据我了解,我可以介绍Redux,但是如果可能的话,我想避免这种情况。
您可以注册回调而不是返回,这样,每当快照变化时,它都会发射,类似的东西:
public GetExercisePosts(user: User, callback: (results: ExercisePost[]) => void) {
const exercisePosts = new Array<ExercisePost>();
firebase.firestore().collection('exercise-posts').where('created-by', '==', user.Id).onSnapshot((results) => {
results.forEach((postDoc) => {
const exercisePost = Deserializer.DeserializeExercisePost(postDoc);
if (exercisePost) {
exercisePosts.push(exercisePost);
}
});
callback(exercisePosts);
});
}
public async componentDidMount() {
const personalExercisePosts = this.exerciseService.GetExercisePosts(this.state.currentUser, (posts) {
this.setState({ posts });
});
}