首页 > 解决方案 > 仅在异步函数中允许等待错误反应本机

问题描述

我是本机反应的新手,并尝试使用将用户对象保存在应用程序存储中await AsyncStorage.setItem('user', res[1].data);
但是我收到错误 消息在此处输入图像描述

handleLogin = async() => {
        NetInfo.fetch().then(state => {
            if (state.isConnected) {

        const {navigate} = this.props.navigation;
        const data = {
            email: this.state.userName,
            password: this.state.password
        };

        fetch(`${DOMAIN_URL}/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
            .then((response) => {
                const statusCode = response.status.toString();
                const data = response.json();
                return Promise.all([statusCode, data]);
            })
            .then((res) => {

                if (res[0] == 200) {
                    await AsyncStorage.setItem('user', res[1].data);
                    navigate('Home');
                }else{
                    Alert.alert(
                        res[1].message
                    );
                }
            })
            .catch((error) => {
                console.error(error);
            });

            }
            else {
                Alert.alert(
                    "No Internet!",
                    "Needs to connect to the internet in order to work. Please connect tablet to wifi and try again.",
                    [
                        {
                            text: "OK",
                            onPress: () => { }
                        }
                    ]
                );
            };
        })
    };

我做了handleLogin异步,但它没有解决错误。存储用户对象的正确方法是什么?

标签: react-nativereact-native-androidasyncstorage

解决方案


推荐使用react-native-easy-app,通过它可以同步访问 AsyncStorage 中的任何数据。

Sample_Hooks

存储控制器


推荐阅读