我试图仅在设备首次打开该设备上时显示该设备上的模式

问题描述 投票:1回答:1

截至目前,每次打开应用程序时,我的代码都会显示模式,我认为这与“ modalVisibility”的初始状态有关

是否[const [modalVisibility,setModalVisibility] = useState(true);”每次启动应用程序都会被调用吗?如果是这样,那就是问题。

“ onShow”模态属性有问题吗?

import React, { useState, useEffect } from 'react';
import { StatusBar, StyleSheet, View, Modal, Text, Button, ScrollView, AsyncStorage } from 'react-native';

export default App = (props) => {

 const [modalVisibility, setModalVisibility] = useState(true);
        const checkIfNeedOpenModal = async () => {
            try {
                const isFirstOpen = await AsyncStorage.getItem('modal');
                if (!isFirstOpen || isFirstOpen !== 'true') {
                    setModalVisibility(true);
                }
            } catch (error) {
                alert(error);
            }
        }

        const saveModalOpen = async () => {
            try {
                await AsyncStorage.setItem('modal', 'true');
            } catch (error) {
                alert(error);
            }
        }
        const onModalShow = () => {
            saveModalOpen();
        }

    useEffect(() => {
        checkIfNeedOpenModal();
    });
return (
        <View style={styles.container}>
            <Modal
                animationType='slide'
                onShow={saveModalOpen}
                transparent={true}
                visible={modalVisibility}
                onRequestClose={() => {
                    alert('closed');
                }}
            >
                <View style={styles.modal}>

                    <ScrollView style={[styles.scrollview, { flex: 1 }]}>
                        <Text>placeholder text</Text>
                    </ScrollView>

                    <View style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
                        <Button
                            title="deny"
                            onPress={() => alert('you must accept the privacy policy to play')}
                        />
                        <Button
                            title="accept"
                            onPress={() => setModalVisibility(false)}
                        />
                    </View>
                </View>
            </Modal>
       </View>
   );
};
react-native modal-dialog asyncstorage use-effect
1个回答
0
投票
我试图复制该示例,但是我无法使其正常工作……任何人都可以帮助我吗?
© www.soinside.com 2019 - 2024. All rights reserved.