Попытка получить доступ к элементам из массива в состоянии - PullRequest
0 голосов
/ 26 марта 2020

Я пытаюсь получить доступ к массиву в моем состоянии в функции. В настоящее время я заполнил массив следующим образом:

loadFollowing() {
var newFollowing = this.state.following
const db = firebase.firestore()
db.collection('users')
  .doc(this.state.uid)
  .collection('following')
  .get()
  .then(snapshot => {
    snapshot.forEach(doc => {
      var newFollower = {
        id: doc.id
      }
      newFollowing.push(newFollower)

    })
    this.setState({
      following: newFollowing
    })

  })

, затем в другой функции я пытаюсь получить доступ к элементам this.state.following так:

loadPosts() {
var newPostList = this.state.postList
var newFollowing = this.state.following
const db = firebase.firestore()
const postCollection = db.collection('posts')
for (let object of newFollowing) {
  postCollection
    .where('creatorId', '==', object.id)
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        var postItem = {
          username: doc.data().username,
          content: doc.data().content,
          creatorId: doc.data().creatorId,
          workoutId: doc.data().workoutId,
          id: doc.id
        }
        newPostList.push(postItem)
      })
    })
    this.setState({
      postList: newPostList
    })
}

Но newFollowing оказывается пустым , Кто-нибудь знает что делать?

1 Ответ

0 голосов
/ 26 марта 2020

Удалить loadPosts() из componentDidMount() и вызвать его, как только вы установитеState в loadFollowing().

loadFollowing() {
  var newFollowing = this.state.following
  const db = firebase.firestore()
  db.collection('users')
    .doc(this.state.uid)
    .collection('following')
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        var newFollower = {
          id: doc.id
        }
        newFollowing.push(newFollower)

      })
      this.setState({
        following: newFollowing
      })
      this.loadPosts();
    })
}

loadPosts() {
  var newPostList = this.state.postList
  var newFollowing = this.state.following
  const db = firebase.firestore()
  const postCollection = db.collection('posts')
  for (let object of newFollowing) {
    postCollection
      .where('creatorId', '==', object.id)
      .get()
      .then(snapshot => {
        snapshot.forEach(doc => {
          var postItem = {
            username: doc.data().username,
            content: doc.data().content,
            creatorId: doc.data().creatorId,
            workoutId: doc.data().workoutId,
            id: doc.id
          }
          newPostList.push(postItem)
        })
      })
    this.setState({
      postList: newPostList
    })
  }   
...