【问题标题】:Im trying to clear AsynStorage on logout我正在尝试在注销时清除异步存储
【发布时间】:2021-01-19 06:14:46
【问题描述】:

我正在使用 react native 开发一个应用程序,并且我在使用 AsyncStorage 时遇到了这个问题。我在登录时存储用户数据,然后在主页上获取数据。我只是想在一条小的欢迎消息中显示用户名,然后如果用户退出,我需要清除存储空间,然后获取下一个用户在设备上登录的存储空间并显示他们的姓名。

问题是我第一次登录时不显示用户名,只有当我退出并重新登录时才会显示名称。不仅如此,它似乎还保留了最后一次登录的人的姓名,并在下次登录时显示该姓名。

任何帮助将不胜感激。

这是我获取并显示用户名的主要代码


    AsyncStorage.getItem('user_data', (err, result) => {
        console.log(result);
        var userdata = JSON.parse(result);
        console.log(userdata);
        firstname = userdata.firstName;
        lastname = userdata.lastName;
    });

    const history = useHistory();
    const doLogout = event => {
        event.preventDefault();
        history.push('/');
        AsyncStorage.removeItem('user_data', (err, result) => {
            console.log(result);
        });
    };

    return (
        <View style={styles.container}>
            <Text>Welcome {firstname} </Text>
            <View style={{ marginTop: 10 }}>
                <TouchableOpacity
                    style={styles.loginbut}
                    activeOpacity={.5}
                    onPress={doLogout}
                >
                    <View style={{ flexDirection: 'row', alignSelf: 'center' }}>
                        <FontAwesomeIcon icon={faSignOutAlt} size={20} style={{ color: '#ffffff' }} />
                        <Text style={{ textAlign: 'center', fontWeight: 'bold', color: 'white' }}> Sign Out </Text>
                    </View>
                </TouchableOpacity>
            </View>
        </View>
     );

} export default MainUI```

【问题讨论】:

    标签: javascript react-native asyncstorage


    【解决方案1】:

    试试这个方法

    async removeItemValue(key) {
        try {
            await AsyncStorage.removeItem(key);
            return true;
        }
        catch(exception) {
            return false;
        }
    }
    

    【讨论】:

      【解决方案2】:

      我觉得如果你想在注销后清除,最好在运行过程中使用reduxcontext来存储用户数据。

      AsyncStorage 就像你想在用户退出进程后存储一些数据。

      比如日志邮件或一些应用设置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-12
        • 2021-06-06
        • 1970-01-01
        • 2020-09-05
        • 1970-01-01
        • 2020-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多