首页 > 解决方案 > 如何从反应本机应用程序中的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);
        });

标签: react-native

解决方案


您可以使用AsyncStorage模块将数据保存在设备存储中。

在这里阅读更多:https ://facebook.github.io/react-native/docs/asyncstorage

收到响应后的示例:

await AsyncStorage.setItem('session_key', student_id);

要检索密钥,您可以使用getItemAsyncStorage 中的方法。

_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


推荐阅读