【问题标题】:Partiall works: Trying to get AsyncStorage object using componentDidMount in React NativePartialall 有效:尝试在 React Native 中使用 componentDidMount 获取 AsyncStorage 对象
【发布时间】:2019-01-12 15:04:46
【问题描述】:

问题是: 如果有用户,App.js 会重定向到 MainPage,我可以得到 AsyncStorage Object

但是如果没有用户,它会重定向到登录页面并且控制台显示 Object 为空(好的,因为如果没有用户我没有设置 Object),并且当它登录时,App. Node.js 设置项目(显示在控制台中)并重定向到 MainPage(但如果我的 AsyncStorage 只显示 {})

主页

async componentDidMount() {
  myArray = await AsyncStorage.getItem('userInfo');
  const d = JSON.parse(myArray);
  console.log('dddddddddddd:',d)
  this.setState({userInfa: d})
}

我的控制台

App.js

componentDidMount() {
 this.authListener();
}
authListener() {
 firebase.auth().onAuthStateChanged(user => {
   if (user) {
     this.setState({ user });
     const userInfo = {
       username: user.displayName,
       emailVerified: user.emailVerified,
       photoURL: user.photoURL,
       userId: user.uid
     }
     AsyncStorage.setItem('userInfo', JSON.stringify(userInfo));
     console.log('userInfo:::::::AAAAAppp', userInfo)
    } else {
     this.setState({ user: null });
   }
  });
  }

我是 react native 的新用户,实际上我不懂 componenDidMount()。希望你能帮忙

【问题讨论】:

    标签: react-native components asyncstorage


    【解决方案1】:

    有了可用的信息量,可能存在两个问题,或者您的 AsyncStorage 没有在本地存储中设置项目(您正在记录本地 const 的 userInfo,您如何知道 AsyncStorage 是否正在设置它)或者您在将其存储在本地存储之前获取它(因为我看到您在存储它时没有使用异步等待)

    【讨论】:

    • 所以我需要在我的 App.js 存储中使用 async/await 吗?
    • 是的。确保将其设置在本地存储中。
    • 在本地存储中设置 getItem 后,在 App.js 中使用它,获取 usrInfo 并记录它。检查是否为空对象。
    • 在上图中记录本地常量。完成 Async.setItem 后通过 Async.getItem 记录
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多