【问题标题】:How to observe changes made to a function that calls firestore onSnapShot?如何观察对调用 firestore onSnapShot 的函数所做的更改?
【发布时间】:2019-07-16 06:48:34
【问题描述】:

我有以下功能:

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 管理控制台添加记录时,它会记录新数据。

如何观察对该快照所做的更改?或者也许让快照发出组件可以侦听的更改?据我了解,我可以介绍 Redux,但我想在这个时候尽可能避免这样做。

【问题讨论】:

    标签: typescript firebase react-native google-cloud-firestore


    【解决方案1】:

    您可以注册一个回调而不是返回,这样当快照更改时它就会触发,如下所示:

    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 });
        });
      }
    

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 2017-06-16
      • 2012-10-14
      • 1970-01-01
      相关资源
      最近更新 更多