【问题标题】:React Native unable to to set AsyncStorage after Fetch APIReact Native 在 Fetch API 之后无法设置 AsyncStorage
【发布时间】:2020-10-24 17:02:14
【问题描述】:

这个问题已经回答了,你可以忽略它并点击离开

我正在使用 react native expo 制作我的应用程序,成功登录后,我的服务器返回一个令牌,我想将它存储在 AsyncStorage 中,这是我的代码:

import { Alert, AsyncStorage } from "react-native";

export const login_as_student = async (code, password, navigation) => {
  return fetch("http://192.168.47.102:5000/users/login/student", {
    // Windows + CMD
    // Wireless LAN adapter Wi-Fi
    method: "POST",
    headers: {
      "content-type": "application/json; charset=UTF-8",
    },
    body: JSON.stringify({ code, password }),
  })
    .then((response) => {
      return response.json();
    })
    .then((json) => {
      const { currentUser, token } = json;
      console.log(json);

      if (token && currentUser) {
        AsyncStorage.setItem("token", token)
          .then((value) => console.log("token", value))
          .catch((error) => console.log(error));

        return navigation.navigate("Darshboard");
      } else {
        console.log(json);
        Alert.alert(json.message);
      }
    })
    .catch((err) => {
      console.log(err);
      Alert.alert(err.message);
    });
};

结果如下:

Object {
  "currentUser": Object {
    "__v": 0,
    "_id": "5f8be6bf0220db23d096ca14",
    "activated": false,
    "code": "16020503",
    "fullname": "Đỗ Xuân An ",
    "password": "$2b$10$PQ5EAc3Vkn1WT00uKadYi.ue2UR1lRBfSeF.cXgZps2pqejV4bAUy",
    "profileImage": "https://avataaars.io/?accessoriesType=Prescription01&avatarStyle=Circle&clotheColor=Blue02&clotheType=BlazerSwet 
er&eyeType=WinkWacky&eyebrowType=FlatNatural&facialHairColor=Platinum&facialHairType=MoustacheFancy&hairColor=Platinum&hatColor=PastelRed&mouthType=Vomit&skinColor=Brown&topType=LongHairMiaWallace",
    "role": "student",
    "vnumail": "16020503@vnu.edu.vn",
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiXCI1ZjhiZTZiZjAyMjBkYjIzZDA5NmNhMTRcIiIsImlhdCI6MTYwMzU1ODYyOSwiZXhwIjoxNjAzNjQ1MDI5fQ.cxOHxddB_ha94ZGXY_XLcCs1MgDJHhZDgbl4GFOzk80",
}
token null

如您所见,我收到了一个包含 2 个对象的 json,即 token 和 currentUser,之后我将它存储在 AsyncStorage 但它返回 null,我是 React Native 的新手,感谢您帮助我美好的一天:)

更新:

谢谢大家,我发现 AsyncStorage 不再是从“react-native”导入的,它现在是从“@react-native-community/async-storage”导入的,祝你有美好的一天

【问题讨论】:

    标签: javascript reactjs react-native asynchronous mobile


    【解决方案1】:

    您在 AsyncStorage.setItem() 之前缺少 await

    像这样修改你的代码:

    .then(async (json) => { // Make this async
      const { currentUser, token } = json;
      console.log(json);
    
      if (token && currentUser) {
       await AsyncStorage.setItem("token", token) // add await here
          .then((value) => console.log("token", value))
          .catch((error) => console.log(error));
    
        return navigation.navigate("Darshboard");
      } else {
        console.log(json);
        Alert.alert(json.message);
      }
    })
    

    【讨论】:

    • 谢谢你的帮助,我已经知道为什么了,我更新了这个问题,祝你有美好的一天
    【解决方案2】:

    你确定你在解构后得到了正确的(非 NULL)令牌和 currentUser 值吗?

    如果您得到空值,请将语句括在括号内 ({currentUser, token} = json)

    另外,一个建议,最好在发布前屏蔽或隐藏令牌值或任何其他敏感信息 :)

    【讨论】:

    • 谢谢你的帮助,我已经知道为什么了,我更新了这个问题,祝你有美好的一天
    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 2018-05-21
    • 2018-01-20
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多