【问题标题】:React Native AsyncStorage.getItem is not working. ({"_40": 0, "_55": null, "_65": 0, "_72": null})React Native AsyncStorage.getItem 不起作用。 ({“_40”:0,“_55”:空,“_65”:0,“_72”:空})
【发布时间】:2020-09-04 06:29:24
【问题描述】:

美好的一天!我有这个 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

【问题讨论】:

    标签: react-native async-await apollo apollo-client asyncstorage


    【解决方案1】:

    我认为您的 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));
    

    【讨论】:

    • Mh 在您返回项目的 .then() 之后附加 .catch() 并没有改变任何东西?同样的第二个代码是错误还是一样的吗?
    • 在附加 .catch() 中,仍然让我出错。我可以使用第二种解决方案,但该文件仅用于功能,它没有反应导入
    • 好的,如果你只是在你得到错误的地方使用你的函数并添加第二个。那么?所以在 .then(item => return item) 之前可能会添加一个 .then(data => data)
    • 迟到的回复。我现在没有错误,非常感谢!
    • 不用担心老兄 gl :)
    猜你喜欢
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多