arrays - 试图从处于状态的数组中访问项目
问题描述
我试图在函数中访问处于我状态的数组。我目前已经像这样填充了数组:
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 是空的,有谁知道该怎么做?
解决方案
一旦你在 .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
})
}
推荐阅读
- windows - GIT 预提交钩子,它在修改/添加的文件中搜索非 UTF-8 编码(如果找到则拒绝提交)
- qt - QT Data Visualization in ROS Workspace Issue
- r - 使用`ddply`从两列中选择基于匹配对的列的最常见值
- javascript - 在 React 中使用 Array.Map() 返回子数组
- r - 比较两个大数据帧的内存有效方法是什么
- php - 我在 laravel 查询语言中遇到错误
- emacs - Cider-connect to already running REPL with figwheel
- java - 如何将两个表的数据合二为一?
- java - Spring @PostConstruct 执行顺序?
- jasmine - 量角器中的失败测试停止了其余测试用例的执行