javascript - 如何将我的集合中的文档放入一个对象数组中,这些对象的字段来自 Google Firestore?
问题描述
我正在创建一个 React 应用程序,它存储它的 Pokedex 条目,以及它在 Google Firestore 上的静态资产。
我有这样的设置:
目标是检索这些 Pokemon 文档并将它们返回到类似于我可以在本地执行的对象数组中。我能够取回条目的控制台日志,但我似乎无法在渲染过程中显示它们中的任何一个,我相信这是由于它们不在数组中。
[{"index": "001", "name": "bulbasaur"},
{"index": "002", "name": "ivysaur"},
{"index": "003", "name": "venesaur"},
{"index": "004", "name": "charmander"},
{"index": "005", "name": "charmeleon"},
{"index": "006", "name": "charizard"},
{"index": "007", "name": "squirtle"},
{"index": "008", "name": "wartortle"},
{"index": "009", "name": "blastoise"},
{"index": "010", "name": "caterpie"},
{"index": "011", "name": "metapod"},
{"index": "012", "name": "butterfree"},
{"index": "013", "name": "weedle"},
{"index": "014", "name": "kakuna"},
{"index": "015", "name": "beedrill"}]
是我的输出。我的代码看起来像这样从“pokedex”集合中检索文档。我希望能够执行一个函数来使用单独条目列出这些条目,这些条目可以使用它们的字段(如索引号和名称)显示,如输出中所示,但是当我使用时我无法在渲染过程中访问它例如“this.state.pokemon[0]”。
state = {
pokemon: null
}
componentDidMount() {
db.collection('pokedex')
.get()
.then( snapshot => {
const testList = []
snapshot.forEach(doc => {
const data = doc.data();
testList.push(data);
})
this.setState({pokemon: testList})
console.log(this.state.pokemon)
})
.catch (error => console.log(error))
}
谢谢
解决方案
尝试下面的代码更新(假设您使用的是 React 类组件),包括将初始 pokemon 状态设置为空数组。您需要明确说明要提取哪些文档字段(即,您需要将“ name
”、“ element
”、“ HP
”替换为您自己的字段)
constructor() {
super();
this.state = {
pokemon: [],
};
}
componentDidMount() {
this.unsubscribe = db.collection('pokedex').onSnapshot(this.getCollection);
}
componentWillUnmount() {
this.unsubscribe();
}
getCollection = querySnapshot => {
const testList = [];
querySnapshot.forEach(res => {
const { name, element, HP } = res.data();
testList.push({
key: res.id,
res,
name,
element,
HP
});
});
this.setState({
pokemon: testList
});
};
推荐阅读
- css - :active 在 div 上立即消失
- laravel - Laravel : 有 Laravel 分析的国家
- spring - spring cloud stream是否支持动态路由,是rabbitmq的特点?
- asynchronous - 我在这里提供的示例是在 C# 中并行运行方法的最佳方式
- amazon-web-services - 需要帮助了解为什么我的 s3 存储桶总是出现 4xx 错误?
- xml - 引起:java.lang.NoSuchMethodException Spring Batch xml配置
- arrays - 如何使用 $in 并使用大于和小于在 mongodb 中查找计数?
- linux - 在 Linux 中使用 LD_PRELOAD 覆盖共享库
- laravel - laravel中的传入和传出好友请求
- c# - 如何拥有非标准名称的外键和相关导航属性