【发布时间】:2018-10-18 15:21:42
【问题描述】:
我正在尝试将数组设置为状态,但它似乎没有设置。 我在下面发布了一些代码。
我想做的是,用户可以将一个项目上传到 firestore 上的主集合,然后这个项目将显示在主屏幕上的主列表中。
我还希望用户能够通过点击他们自己的个人资料来查看他们自己的项目,并且他们可以看到只有这些项目的列表。
我采用的方法是将项目上传到 firestore 上的主集合,然后将文档 ID 和集合引用(即“c”)都放入名为 userItems 的子集合中的文档中,其中特定用户的文档。我认为这是最好的方法,所以我只有“1 个事实来源”,不必担心重复,特别是如果我将来必须更新任何文档。
正如我在顶部所说,我的问题是一旦我尝试在第二个方法“queryUserItems”中迭代它,数组就是空的。如果有人能够指出我做错了什么,我将非常感激,或者如果有人能够指出我最终想要做的更优雅和有效的方式,那就是: 以可以从主列表和用户自己的列表中查看的方式保存项目,这有点像 Instagram 的工作方式。
感谢您的帮助:)
UserProfile.js
constructor() {
super();
this.getUserItems = this.getUserItems.bind(this);
this.state = {
Name: '',
Location: '',
items: [],
Keys: [],
test: ''
};
}
componentDidMount() {
console.log('UserProfile');
this.getUserItems();
//this.queryKeys();
}
getUserItems = () => {
const Keys = [];
const userCollectionRef = firebase.firestore()
.collection('a').doc('b')
.collection('c')
userCollectionRef.get()
.then((querySnapshot) => {
console.log("user doc received");
querySnapshot.forEach(function (doc) {
console.log('Doc.id: ', doc.id);
console.log('Doc.Key: ', doc.data().Key);
console.log('Doc.CollectionRef: ', doc.data().CollectionRef);
const {Key, CollectionRef} = doc.data();
Keys.push({
Key,
CollectionRef
})
}); // foreach loop end
this.queryKeys(keys);
}).catch(function (error) {
console.error("getUserItems => error: ", error);
});
// this.setState(() =>({
// Keys,
// test: 'testString'
// }));
console.log("Keys inside: ", Keys);
};
queryKeys(keys) {
const items = [];
console.log("queryKeys Called!");
console.log("queryKeys :", keys);
console.log('test: ', this.test);
keys.forEach(function(Key, CollectionRef) {
console.log("Key array: ", Key);
console.log("CollectionRef array: ", CollectionRef);
firebase.firestore
.collection('a').doc('b')
.collection(CollectionRef)
.doc(Key)
.get().then(function (doc) {
console.log("doc received");
const {Name, imageDownloadUrl, Location} = doc.data();
items.push({
key: doc.id,
doc, // DocumentSnapshot
Name,
imageDownloadUrl,
Location,
});
}).catch(function (error) {
console.error("queryKeys: error: ", error);
})
}) // forEach end
this.setState({
items
});
}
更新:
我决定采用不同的方法,我只是在 .then 的末尾调用 queryKeys 函数,然后在 getUserItems 中传递键作为参数。这种方式似乎有效,因为它在正确的时间获取了数组,但现在我从 firestore 收到错误:
当我这样做时:
firebase.firestore
.collection('a').doc('b')
.collection('c')
.doc('docID').get()
.then((doc) => {
如何通过 id 获取文档?
谢谢
【问题讨论】:
-
您的代码的异步性质存在问题,您的 setState 在循环完成之前被调用。您需要在项目全部完成后设置状态
-
getUserItems和queryKeys都执行异步函数。getUserItems在调用queryKeys之后设置状态,因为它从外部源获取数据。getUserItems应该返回一个承诺,或者你可以使用async/await,但它应该返回Keys,然后将它们传递给queryKeys -
我尝试在 .then 在 for 循环的末尾调用 'getUserItems' 函数中的 'queryKeys' 函数,但后来我在调用 queryKeys 函数时遇到了问题,我一直收到说 queryKeys 的错误不是功能。即使我觉得这样做更好。谢谢你们的评论
标签: javascript firebase react-native google-cloud-firestore