Moh*_*h75 1 javascript async-await react-native 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;
Run Code Online (Sandbox Code Playgroud)
因此,如果这是用户第一次打开应用程序,operator则为 null 或未定义(我尝试了两者但没有结果)-(然后在用户登录后,LoginForm我会将其更改为operator“john”之类的内容)。
但它<Router />由于某种原因返回了(考虑到isLoggedIn逻辑上必须是假的,但是......)
我也试着setItem该节进行测试,但再没有结果:
componentWillMount() {
AsyncStorage.setItem("operator", "John");
const temp = AsyncStorage.getItem("operator");
console.log(temp);
}
Run Code Online (Sandbox Code Playgroud)
但console.log(temp);说undefined了!
为什么我不能使用setItem然后使用获取数据getItem?
提前致谢!
AsyncStorage 是异步的:-)。在其返回的承诺解决之前,提交的值不可用。作为这种不便的交换,它不会在写入过程中阻塞您的 JavaScript 线程。
如果你试试:
AsyncStorage.setItem("operator", "John").then(
() => AsyncStorage.getItem("operator")
.then((result)=>console.log(result))
)
Run Code Online (Sandbox Code Playgroud)
你应该得到你所期望的。(这也可以使用 async/await 来完成,如AsyncStorage 文档中所示)。
您并没有真正向我们展示如何将 props 输入到您的应用程序中,但是如果您在 上更新值时更新<App>的 props ,则您的组件应该相应地更新。isLoggedInthen
| 归档时间: |
|
| 查看次数: |
3387 次 |
| 最近记录: |