【发布时间】:2019-03-29 15:02:41
【问题描述】:
我正在尝试在我的 react 本机应用程序中使用 asyncstorage。问题是我得到的服务器响应需要一些延迟,所以我想等待响应然后我想使用该 responseData.user_id 来保存我的应用程序。我使用 nodejs 作为后端和 mysql db。所以在用户注册后,我将它插入到 db,同时我编写了另一个查询来获取他们的 user_id (PK)。所以这个 responseData 正在到达客户端我正在尝试从响应中获取那个 user_id。所以我写了这样的东西
onPressRegister = async () => {
try {
let response = await fetch('http://192.168.1.2:3000/users/registration', {
method: 'POST',
headers: {
'Accept': 'applictaion/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
contact: this.state.contact,
password: this.state.password,
})
});
let responseData = await response.json();
if (responseData) {
try {
Action.firstScreen();
await AsyncStorage.setItem('userid', JSON.stringify(responseData.userData.phone_no));
}
catch (e) {
console.log('caught error', e);
}
}
} catch (error) {
console.error(error)
}
}
在我的下一个屏幕中,我将像这样访问用户 ID。然后像这样传递下一个 API 调用。
getUserId = async () => {
let userId = await AsyncStorage.getItem('userid');
return userId;
}
onPressYes = (workType) => {
this.getUserId().then((userId) => {
this.setState({userId:userId})
})
fetch('http://192.168.1.2:3000/users/user_request',{
method:'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
workType,
phone:this.state.userId
})
})
.then(response => response.json())
.then((responseData) => {
this.setState({
data:responseData
});
});
}
【问题讨论】:
-
你是正确的
await AsyncStorage.setItem...所以你为什么不let usid = await AsyncStorage.getItem('userid');等待价值可能更重要 -
如果不加
try,可以看看你的问题是什么。 -
`data: '用户注册成功', userData: { pwd: 'mkmk', phone_no: '23', user_name: '', status: 1, date: 2018-10-25T05:31 :12.358Z }, user_id: 16, token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.}` 这就是 responseData 的样子,问题是我可以在 asyncstorage 中设置令牌,但不能在 user_id..strange 中设置。请看@987654322 @
-
AFAIK
AsyncStorage仅存储字符串值。所以你应该在你的setItem电话中尝试JSON.stringify(responseData.user_id)之类的东西。 -
您的原始代码似乎有一个随机行,其中声明了函数
async getCache(userid){...}。这就是导致输出错误的原因。为什么要在处理代码的过程中声明一个函数?
标签: javascript react-native async-await asyncstorage