React Native AsyncStorage.getItem 不工作。 ({“_40”:0,“_55”:空,“_65”:0,“_72”:空})

React Native AsyncStorage.getItem is not working. ({"_40": 0, "_55": null, "_65": 0, "_72": null})

美好的一天!我有 AsyncStorage 的这个功能,它获取一个令牌项。我使用 ApolloClient 来处理令牌,但是当我第一次测试它时,它似乎有一个错误,我将通过 AsyncStorage 函数获得什么。

export function jwtLogin(data) {
  return async dispatch => {
    const userData = {
      email: data.email,
      password: data.password,
    };
    console.log(userData);
    const client = new ApolloClient({
      link: new HttpLink({
        uri: API_URL,
      }),
      cache: new InMemoryCache(),
    });
    client
      .mutate({
        mutation: loginUser,
        variables: {
          email: userData.email,
          password: userData.password,
        },
      })
      .then(resp => {
        console.log(resp.data.tokenCreate);
        console.log('Token', resp.data.tokenCreate.token);
        if (resp.data.tokenCreate.token !== null) {
          saveJWTTokenData(resp.data.tokenCreate.token); //from AsyncStorage save function

          async function main() { //function of AsyncStorage
            await AsyncStorage.getItem('jwt_token').then(item => {
              return item;
            });
          }
          console.log(main()); // returns error
          Actions.push('main_loading');
        } else {
          const errors = resp.data.tokenCreate.errors;
          {
            errors.map(err => {
              Alert.alert('Error.', err.message);
            });
          }
        }
      })
      .catch(err => {
        Alert.alert('Error.', err.message);
      });
  };
}

对于保存存储功能:

export const saveJWTTokenData = async jwt_token => AsyncStorage.setItem('jwt_token', jwt_token);

My Error Log Picture

我认为你的 Promise 处理不正确..

尝试在你的 then 调用之后添加一个 catch,如下所示:

.catch(err => console.log(err))

或者尝试像这样使用你的函数:

      await getData("jwt_token")
    .then(data => data)
    .then(value => this.setState({ token: value })) // here it is setState but I guess you can also return
    .catch(err => console.log("AsyncStorageErr: " + err));