尝试从状态数组中访问项目

时间:2020-03-26 11:37:27

标签: arrays react-native loops

我正在尝试访问处于我状态的函数中的数组。目前,我已经像这样填充数组:

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。的元素,如下所示:

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 :(得分:0)

loadPosts()中删除componentDidMount(),并在loadFollowing()中设置setState后调用它。

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