【发布时间】:2019-12-05 12:29:50
【问题描述】:
我正在从 firestore 读取数据并将其存储在对象的状态数组中。
当我
console.log(this.state.array)
它返回整个数组以及对象的所有数据,但是当 i
console.log(this.state.array.name)
或
console.log(this.state.array[0])
它返回未定义
.
我试图用
获取数据forEach
循环,但似乎效果不佳。
constructor(props) {
super(props);
this.state = { tips: [] };
}
componentDidMount() {
firebase.firestore().collection('pendingtips').get()
.then(doc => {
doc.forEach(tip => {
this.setState([...tips], tip.data());
console.log(this.state.tips);
});
})
.catch(() => Alert.alert('error'));
}
renderTips() {
console.log(this.state.tips); //returns the whole array as expected
console.log(this.state.tips[0].name); //returns undefined
return this.state.tips.map(tip => <PendingTip key={tip.tip} name={tip.name} tip={tip.tip} />); //return null because tip is undefined
}
render() {
return (
<View style={styles.containerStyle}>
<ScrollView style={styles.tipsContainerStyle}>
{this.renderTips()}
</ScrollView>
</View>
);
}
数组结构为:
"tips": [
{ name: "X", tip: "Y" },
{ name: "Z", tip: "T" }
]
所以我希望 this.state.tips[0].name 将是“X”而不是未定义。
提前致谢。
【问题讨论】:
-
你能在beakpoint分享这个阵列的打印屏幕吗?
标签: javascript arrays reactjs react-native