【发布时间】:2019-02-25 08:42:12
【问题描述】:
我已经尝试调试了几个小时,但无济于事。我编写了这个脚本,基本上在组件加载时从我的 Firestore 数据库中获取信息。然后我将数组中的一项记录到控制台,得到undefined。我不明白为什么它可以显示完整的数组但不能显示一个项目。然后整个 Array 产生完整的数组(部分图像见下)。
该组件的主要目标是生成列表组件中的项目列表,但没有显示任何内容。我的第一个猜测是从数据库获取信息的方法是异步的,但是如果状态更新了,这有关系吗?应用程序不应该重新渲染吗?
这是我的代码的 sn-p,非常感谢您的帮助!
export default class ItemScreen extends Component {
constructor () {
super()
this.state = {
items: [],
}
}
componentDidMount() {
var items = []
firebase.firestore().collection("items").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
items.push(doc.data());
});
})
this.setState({items: items});
console.log(items[1])
console.log(items)
}
render() {
const { items } = this.state
return (
<View style={styles.container}>
<SearchBar
lightTheme
onChangeText={(text) => console.log(text)}
onClearText={() => console.log("cleared")}
placeholder='Type Here...'
containerStyle={{width: "100%"}}
/>
<List containerStyle={{width: "100%"}}>
{
items.map((l) => (
<ListItem
roundAvatar
avatar={{uri:l.image}}
key={l.name}
title={l.name}
/>
))
}
</List>
</View>
);
}
}
【问题讨论】:
-
你有一个 Promise
.get().then(,记住在 JS 中你没有 I/O 阻塞,这意味着当你使用 Promise 时异步执行代码,只将日志关闭发送到then -
当 IO 尝试这样的事情时,我收到一个错误,即 this.state 不是函数。见下文
标签: javascript firebase react-native google-cloud-firestore