javascript - 数组 setState 和获取数组 React Native
问题描述
我正在尝试将数组设置为状态,但它似乎没有被设置。我在下面发布了我的一些代码。
我要做的是,用户可以将一个项目上传到 firestore 上的主集合,然后这个项目将显示在主屏幕上的主列表中。
我还希望用户能够通过单击他们自己的个人资料来查看他们自己的项目,并且他们可以看到只有这些项目的列表。
我采取的方法是将项目上传到firestore上的主集合,然后将文档ID和集合引用(即“c”)都放入名为userItems的子集合中的文档中,并且在该特定用户的文档中. 我认为这是最好的方法,所以我只有“1 个事实来源”,不必担心重复,特别是如果我将来必须更新任何文档。
正如我在顶部所说,我的问题是一旦我尝试在第二个方法“queryUserItems”中迭代它,数组就是空的。如果有人能够指出我做错了什么,我将非常感激,或者如果有人能够指出我最终想要做的更优雅和有效的方式,那就是:储蓄这些项目可以从主列表以及用户自己的列表中查看,有点像 Instagram 的工作方式。
感谢您的任何帮助 :)
用户配置文件.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
});
}
更新:
我决定采用不同的方法,我只是queryKeys
在 .then in 末尾调用函数,getUserItems
然后将键作为参数传递。这种方式似乎有效,因为它在正确的时间获取了数组,但现在我从 firestore 收到错误消息:
当我这样做时:
firebase.firestore
.collection('a').doc('b')
.collection('c')
.doc('docID').get()
.then((doc) => {
如何通过 id 获取文档?
谢谢
解决方案
我在下面所做的修改非常脏,我怀疑您的问题是您在循环执行之前在上面的两种方法中都调用了 setState 。
您正在同步循环,在循环内执行异步操作,退出循环(同步)并调用 setState,期望数组被循环内获取的数据填充,这不会发生,因为您不是等待对 Firebase 的 AJAX 请求。
我在下面所做的是将 setState 的调用放在每个循环中的 promise 的解析中,这并不理想(实际上,这对于生产来说是一个糟糕的主意),因为它会更新每个项目的状态列表,而不是在收集完所有数据后。你需要做那个循环,有很多方法可以做到这一点。它应该可以证明这一点,并且您应该在屏幕上看到数据。
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
})
});
this.setState(() =>({
Keys,
test: 'testString'
}));
}).catch(function (error) {
console.error("getUserItems => error: ", error);
});
console.log("Keys inside: ", Keys);
};
queryKeys() {
const items = [];
console.log("queryKeys Called!");
console.log("queryKeys :", this.state.Keys);
console.log('test: ', this.test);
this.state.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,
});
this.setState({
items
});
}).catch(function (error) {
console.error("queryKeys: error: ", error);
})
}) // forEach end
}
下面您将看到一个粗略的示例,说明如何使用 async 和 await 使循环异步,不确定 Firebase API 是否可以很好地处理此问题,您可能需要阅读他们的文档。
queryKeys() {
const items = [];
console.log("queryKeys Called!");
console.log("queryKeys :", this.state.Keys);
console.log('test: ', this.test);
this.state.Keys.forEach(async function(Key, CollectionRef) {
console.log("Key array: ", Key);
console.log("CollectionRef array: ", CollectionRef);
try {
let result = await firebase.firestore
.collection('a').doc('b')
.collection(CollectionRef)
.doc(Key)
.get();
const {Name, imageDownloadUrl, Location} = result.data();
items.push({
key: doc.id,
doc, // DocumentSnapshot
Name,
imageDownloadUrl,
Location,
});
} catch (e) {
console.error("queryKeys: error: ", error);
}
}) // forEach end
this.setState({
items
})
}
推荐阅读
- php - Twillio - 获取传入短信的内容
- javascript - 使用多个系列的xAxis的Highcharts问题
- spring - 在 Spring Boot 应用程序中连接到多个数据库模式
- c++ - 尝试将文件中的字符串读入无符号字符向量
- python - 为什么 Scrapy Udemy 给出响应 403 错误?
- office365 - Office 365 IMAP 访问的 OAuth 身份验证支持
- javascript - 无法让我的范围滑块正确显示值
- python - OpenCV-contrib/Python/Windows:Tracker.write() 在 matrix_wrap.cpp 中引发错误,Tracker.read() 使 Python 崩溃
- javascript - MapBox - 如何禁用 mapbox-gl-js 中的所有移动,除了旋转和缩放到设定点
- javascript - azure 函数接收 iothub 消息并保存到 CosmoDB