React Native Firebase -首次加载时无法检索状态

uqdfh47h  于 2022-12-14  发布在  React
关注(0)|答案(1)|浏览(105)

我使用useEffectreact-native应用程序的初始屏幕加载时检索一些用户和组数据。

const [groupInfo, setGroupInfo] = useState([]);
    //Called on INITIAL rendering
useEffect(() => {

    async function getGroupData() {

        let groupCode = '';

        //Retrieve group code from user
        await getDoc(doc(db, 'users', email)).then(userSnapshot => {

            if (userSnapshot.exists()) {
                groupCode = userSnapshot.data()['group_code'];

            }
            else { console.log('No user with that email exists!'); }
        }).catch(err => {
            console.log(err);
        });

        //Retrieve group information from user
        await getDoc(doc(db, 'groups', groupCode)).then(groupSnapshot => {

            if (groupSnapshot.exists()) {
                setGroupInfo(groupSnapshot.data());
            }
            else { console.log('No group with that code exists!'); }
        }).catch(err => {
            console.log(err);
        });
    }

    getGroupData();

}, [email]);

问题是当我尝试在return语句上渲染这个视图时,我得到了一个错误。我之前记录了我的数据,工作正常,但似乎应用程序先加载了视图。下面是React渲染代码和错误:

return (
    <View style={styles.container}>
        <View style={styles.header}>
            <Text style={styles.headerLeft}>Goals</Text>
            <Text style={styles.headerRight}>Week of 11/20/22</Text>
        </View>
        <Text style={styles.prize}>Prize: Winner gets a free starbucks drink!</Text>
        {/*<View style={styles.goalBox}>
            <Text>Workout 3x per week</Text>
            <CheckBox style={styles.checkbox}/>
        </View> */}

        {/* TODO edit prize screen */}
        <Button title="Edit prize" />

        <View style={styles.memberHeader}>
            <Text style={styles.headerLeft}>Members</Text>
            <Text style={styles.numMembers}>4</Text>
        </View>

        {
            groupInfo['members'].map((memberName, index) =>
                <View style={styles.member}>
                    <Text style={styles.memberText}>{memberName}</Text>
                </View>
            )
        }
        
        <Button title="Invite member" />
    </View>
);

错误:

ERROR  TypeError: Cannot read property 'map' of undefined

This error is located at:
    in ScreenViewGroup (created by SceneView)

编辑:
因此,我认为问题是在呈现组件的同时,数据也在加载。我仍然收到同样的错误,但我注意到当我编辑代码时,数据会自动加载。
文本字符串似乎也能正确地呈现,但数组不能。

tkclm6bt

tkclm6bt1#

所以我找到了一个解决办法,通过声明初始数组的值,React会将这些值作为默认值填充,并在加载时立即将其更改为firebase值。

相关问题