我如何使用异步存储保存数据在本地调用fetch在react native后?



我想使用异步存储。每次我调用没有async函数的时候,就像这样

FunctionLogin = () =>{ //other methods here ........ }

,这没有等待任何地方,它保存到数据库,但当我使用let email = AsyncStorage.getItem('email');要回调它,它不会返回任何东西,就像电子邮件只是[Object Object]是我看到的

如何解决这个

保存到异步存储的获取方法如下所示

`FunctionLogin = async () =>{
//navigation.replace('VirtualAccountPage');
let item = {email, password,phone};
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(responseJson =>{
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}`

调用回调它的函数,因此它可以作为持久性的外观使用,因此

`  FunctionUserDetails = () => {
let email  = AsyncStorage.getItem('email');
let phone  = AsyncStorage.getItem('telephone');
//navigation.replace('Dashboard');
alert(email);
};`

我如何得到这个工作?

我希望能够使用异步存储在本地保存数据,这样我就可以在其他一些屏幕上持久化数据等。我尝试了几件事,看看它是否能像预期的那样工作,我没有看到它像我想要的那样工作。

要从AsyncStorage中获得值,您需要使用await,该函数应从async开始

fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
const FunctionUserDetails = async () => { // change this
let email  = await AsyncStorage.getItem('email'); // change this
let phone  = await AsyncStorage.getItem('telephone'); // change this
//navigation.replace('Dashboard');
alert(email);
};`

安装更新后的async-storage npm

尝试使用下面的代码实现:

fetch('https://xxxx/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.stausCode === 200) {
await AsyncStorage.setItem('name', name);
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});

最新更新