React native 仅在异步函数中允许等待错误反应本机
我不熟悉react native并尝试使用React native 仅在异步函数中允许等待错误反应本机,react-native,react-native-android,asyncstorage,React Native,React Native Android,Asyncstorage,我不熟悉react native并尝试使用await AsyncStorage.setItem('user',res[1].data)将用户obejct保存在应用程序存储中但我得到的错误如下: 我已经使handleLogin异步,但它没有解决错误。存储用户obejct的正确方法是什么?建议您使用,通过它可以同步访问异步存储中的任何数据 navigateToHome = async (user) => { const { navigate } = this.props
await AsyncStorage.setItem('user',res[1].data)将用户obejct保存在应用程序存储中代码>
但我得到的错误如下:
我已经使handleLogin
异步,但它没有解决错误。存储用户obejct的正确方法是什么?建议您使用,通过它可以同步访问异步存储中的任何数据
navigateToHome = async (user) => {
const { navigate } = this.props.navigation;
await AsyncStorage.setItem('user', user);
navigate('Home');
}
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
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) {
navigateToHome(res[1].data);
}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: () => { }
}
]
);
};
})
};
await
在的回调函数中。然后()
该箭头函数不是异步的。我创建了一个新的异步函数,名为navigateToom,它工作正常。
navigateToHome = async (user) => {
const { navigate } = this.props.navigation;
await AsyncStorage.setItem('user', user);
navigate('Home');
}
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
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) {
navigateToHome(res[1].data);
}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: () => { }
}
]
);
};
})
};