javascript - 没有将值传递给组件 - React Native
问题描述
我正在从 cloud firestore 作为对象数组检索数据,并将对象的值作为道具传递给另一个组件:
renderTips() {
firebase.firestore().collection('pendingtips').get()
.then(doc => {
doc.forEach(tip => {
const tipData = tip.data();//array's object
console.log(tipData.tip); //prints tip as expected
console.log(tipData.name); //prints name as expected
return <PendingTip key={tipData.tip} name={tipData.name} tip={tipData.tip} />; //doesn't returning enything
});
})
.catch(() => Alert.alert('error'));
}
render() {
return (
<View style={styles.containerStyle}>
<ScrollView style={styles.tipsContainerStyle}>
{this.renderTips()}
</ScrollView>
</View>
);
}
对象数组如下所示:
{ name: 'Danny', tip: 'Be careful when crossing the road' },
{ name: 'Alex', tip: 'Drink water' }
期望在我的 ScrollView 中我会有一个“提示”列表。相反,我一无所获,就好像这些值没有传递给组件一样。
提前致谢。
解决方案
RenderTips 返回一个promise,这意味着它在第一次渲染时不会返回任何东西,但只有在promise 解决时才会返回。您需要在 renderTips 中使用 setState 来告诉 react 在数据到来时重新渲染您的组件。为 pendingTips 创建一个单独的状态数组对象,然后将 pendingTips 组件添加到该数组并调用 setState
this.state = { pendingTips: [] }
componentDidMount() {
let pendingTips = [] // declare an array
firebase.firestore().collection('pendingtips').get()
.then(doc => {
doc.forEach(tip => {
const tipData = tip.data();//array's object
pendingTips.push(<PendingTip key={tipData.tip} name={tipData.name} tip={tipData.tip} />); // push items in the array
});
this.setState({pendingTips})
})
.catch(() => Alert.alert('error'));
}
render() {
return (
<View style={styles.containerStyle}>
<ScrollView style={styles.tipsContainerStyle}>
{this.state.pendingTips.map(tips => tips)}
</ScrollView>
</View>
);
}
推荐阅读
- javascript - 在 JSON 中存储样式值的最佳方式
- sql-server - 通过用NULL替换数据来缩小数据库?
- html - 访问 Web 服务器上的图像时出现奇怪的权限被拒绝问题
- r - 如何使用 ', pattern = ' 从可能的后缀列表中选择文件
- typescript - Vue 3/Typescript:找不到模块 xxx 或其相应的类型声明。威图尔(2307)
- flutter - 为什么颤振“等待”不等待?
- css - 使用 text-align 与 flexbox 的 align-items 对齐文本之间是否存在显着差异(性能或其他方面)?
- java - 从字符串中提取字符串的某些部分的正确正则表达式是什么
- html - 使图像成为卡片的头部| 引导程序
- javascript - 如何让按钮播放乐蒂动画,同时在里面