我已经尝试调试了几个小时,但无济于事。我写了这个脚本,基本上当组件加载时从我的 Firestore 数据库中获取信息。然后,我将数组中的一项记录到控制台,结果为 undefined
。我不明白为什么它可以显示完整的数组而不是一个项目。然后整个阵列产生完整阵列(见下图的部分图像)。
此组件的主要目标是生成列表组件中所见但未显示任何内容的项目列表。我的第一个猜测是从数据库中获取信息的方法是异步的,但是如果更新了状态,这会很重要吗?应用程序不应该重新渲染吗?
这是我的代码片段,非常感谢您的帮助!
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>
);
}
}
最佳答案
尝试重组为更像的东西
var items = []
var self = this;
firebase.firestore().collection("items").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
items.push(doc.data());
});
self.setState({items: items});
console.log(items[1])
console.log(items)
})
原始方法底部的代码会在结果可用之前运行。
关于javascript - React Native - 无法获取数组中的项目,或无法在列表中显示数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52435240/