首页 > 解决方案 > 没有将值传递给组件 - 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 中我会有一个“提示”列表。相反,我一无所获,就好像这些值没有传递给组件一样。

提前致谢。

标签: javascriptarraysreactjsfirebasereact-native

解决方案


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>
        );
    }

推荐阅读