首页 > 解决方案 > 试图从处于状态的数组中访问项目

问题描述

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

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 是空的,有谁知道该怎么做?

标签: arraysreact-nativeloops

解决方案


一旦你在 .setState 中删除并loadPosts()调用它。componentDidMount()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
    })
  }   

推荐阅读