反应本地异步存储不起作用

时间:2018-07-10 22:29:20

标签: javascript react-native async-await asyncstorage

我正在尝试进行身份验证,因此我的App.js:

import React, { Component } from "react";
import { AsyncStorage } from "react-native";
import Router from "./Router";
import ScanForm from "./components/ScanForm";

console.disableYellowBox = true;

class App extends Component {
  state = {
    isLoggedIn: false
  };

  componentWillMount() {   
    const temp = AsyncStorage.getItem("operator");
    console.log(temp);

    if (temp !== undefined) {
      this.setState({ isLoggedIn: true });
    }
  }

  render() {
    if (this.state.isLoggedIn) {
      return <ScanForm />;
    } else {
      return <Router />;
    }
  }
}

export default App;

因此,如果这是用户第一次打开应用,则operator为null或未定义(我尝试过两次但都没有结果)-(然后在LoginForm中,我将更改{{1 }},例如在用户登录后输入“ john”。

但是出于某种原因它返回了operator(考虑到<Router />在逻辑上必须为假,但是...)

我也曾尝试在该部分中 setItem 进行测试,但再次没有结果:

isLoggedIn

但是componentWillMount() { AsyncStorage.setItem("operator", "John"); const temp = AsyncStorage.getItem("operator"); console.log(temp); } 再说一次console.log(temp);

为什么我不能使用undefined然后用setItem来获取数据?

  

谢谢!

1 个答案:

答案 0 :(得分:4)

AsyncStorage是异步 :-)。在其返回的承诺解决之前,承诺的值不可用。作为这种不便的交换,在编写过程中,它不会阻止您的JavaScript线程。

如果您尝试:

AsyncStorage.setItem("operator", "John").then(
   () => AsyncStorage.getItem("operator")
         .then((result)=>console.log(result))
)

您应该得到期望的结果。 (这也可以使用AsyncStorage docs中所示的async / await来完成。)

您并没有真正向我们展示如何将道具输入应用程序,但是如果在<App>上更新值时用isLoggedIn更新then的道具,您的组件应相应更新。

相关问题