我正在使用 AsyncStorage.setItem
在服务器上设置数据,并尝试使用 AsyncStorage.getItem
在另一个屏幕中访问该值。
1. 我无法在 AsyncStorage
中设置token
。
2. 如何在 asyncstorage 中设置多个值,假设我希望将服务器响应中的 user_id
与此 token
一起设置?
onPressRegister(){
fetch('http://192.168.1.7:3000/users/registration',{
method:'POST',
headers:{
'Accept': 'applictaion/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
contact:this.state.contact,
password:this.state.password,
})
})
.then((response) => response.json())
.then((responseData) =>
{
this.setState({
signup: responseData
});
setTimeout(() => {
Actions.firstScreen();
}, 2300);
AsyncStorage.setItem('token' ,this.state.signup.token);
});
}
我是这样获取的
componentDidMount(){
AsyncStorage.getItem('token').then((userid) =>{
this.setState({'userid': userid});
console.log(userid);
});
}
但是我在控制台
中看不到结果,什么也没有得到。 AsyncStorage.setItem
中是否有任何错误?此外,服务器响应如下所示
{ error: 0,
data: 'User registered Successfully',
userData:
{ pwd: 'vgh',
phone_no: '5',
user_name: '',
status: 1,
date: 2018-10-23T09:23:53.671Z },
user_id: [ { user_id: 5 } ],
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' }
此外,我希望在 AsyncStorage
中设置 user_id
。这个怎么做?
最佳答案
您可以使用async
和await
来访问AsyncStorage中的值。
async componentDidMount(){
let token = await AsyncStorage.getItem('token');
console.log(token);
}
关于javascript - React Native 中的 AsyncStorage.getItem 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945727/