为什么 AsyncStorage getItem 返回 null?

Why AsyncStorage getItem is returning null?

export const USER_KEY = "isLoggedIn";

export const phoneVerified = () => AsyncStorage.setItem(USER_KEY, 1);
export const userInfoVerified = () => AsyncStorage.setItem(USER_KEY, 2);

我使用上面的函数来存储值,下面的函数来获取值。

export const isSignedIn = () => {
  return new Promise((resolve, reject) => {
    AsyncStorage.getItem(USER_KEY)
      .then(res => {
          console.log("from isSignedIn : "+res); //res is showing null.
        if (res !== null) {
          resolve(res);
        } else {
          resolve(0);
        }
      })
      .catch(err => reject(err));
  });
};

为什么这总是 returns null?我正在尝试 async/await 但仍然为空。我想不知何故数据没有存储。

恐怕你只能存储字符串。请参考这个 and this https://facebook.github.io/react-native/docs/asyncstorage.html#setitem

谢谢。

正如@Vishu Bhardwaj 的回答,AsyncStorage 只接受字符串。所以你可以在这种情况下使用 JSON.stringify()JSON.parse()

我被这个愚蠢的问题困扰了将近一个星期,所有社区中没有其他建议的方法对我有用,但后来我发现了一些由 react-native 构建的东西,它的 setState() 回调函数: https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296。 所以我保证这是迄今为止唯一安全的方法的唯一方法是你在你的承诺中使用 setState() 函数以及你需要 运行 的所有东西,把它们放在一个函数上并为setState() 回调函数,这是您可以确保自己既不会得到 null 也不会调用该函数的唯一方法。在这里,我将提供一个示例,其中 this.tokeToServer() 是我的函数,它用作回调函数。

try {
      AsyncStorage.getItem('firebase_token',(err,item) => {
        if (item) {
          this.setState({
            firebase_token: item,
          }),this.tokenToServer();
        }
      });
      } catch (error) {
      console.log("Error retrieving data" + error);
    }

根据朋友 Abdu4 的介绍,我遇到了同样的问题 4 天,并搜索了不同的站点和论坛。尝试 async/await 和其他人,即使你应该使用这些选项,你完成并真正工作的是通过回调

通过 setState 分配值
try {
        AsyncStorage.getItem('TOKEN_KEY',(err,item) => {
            if (item) {
                setToken({
                    Token: item,
                });
            }
        });
    } catch (error) {
        console.log("Error retrieving data" + error);
    }