react-native - 如何从反应本机应用程序中的json数据设置会话中的student_id?
问题描述
如何根据从反应原生应用程序中的 API 接收的 JSON 数据在设备会话中设置 student_id?
{"data":{"user":"user1","pass":"123456","student_id":"54","name":"test","student_birthdate":"1981-10-10","student_roll_no":"303","student_standard":"7","student_phone":"1234567890"},"responce":true}
fetch('http://192.168.0.2/index.php/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Userid: user,
Upassword: pass
})
}).then((response) => response.json())
.then((responseJson) => {
//console.log('response object:',responseJson)
}).catch((error) => {
console.error(error);
});
解决方案
您可以使用AsyncStorage
模块将数据保存在设备存储中。
在这里阅读更多:https ://facebook.github.io/react-native/docs/asyncstorage
收到响应后的示例:
await AsyncStorage.setItem('session_key', student_id);
要检索密钥,您可以使用getItem
AsyncStorage 中的方法。
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('session_key');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
编辑:
来自您服务器的数据似乎是字符串化的。您需要将该数据解析为 JSON。
尝试这个:
const responseFromServer = JSON.parse(responseJson);
现在,responseFromServer
应该包含 data 属性。您可以像这样访问它:
responseFromServer.data.student_id
推荐阅读
- c# - 使用 C# 创建子域
- angular - 如何显示您的 404 页面?
- android - 具有自定义背景的文本视图中的表情模糊
- javascript - 将 x 分成 y 部分的随机数,最大值为 n
- angular - Charge-bee 与 angular 4 的集成
- r - R函数从网络中一个一个地删除节点并输出最大的连通分量
- python - PyMOL 在 Python 3 上工作
- php - 使用 alamofire 4 在 swift 4 中上传图像,而 php 在更新版本中不起作用
- ios - 如何将动画添加到切换视图?
- android - 片段中 RecyclerView 中的 OnClickListener