反应本机异步存储不工作
react native Async Storage not working
我正在尝试进行身份验证,因此我的 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
中我将更改 operator
到用户登录后类似 "john" 的内容。
但由于某种原因它返回了 <Router />
(考虑到 isLoggedIn
在逻辑上一定是错误的但是...)
我也尝试在该部分中 setItem 进行测试,但再次没有结果:
componentWillMount() {
AsyncStorage.setItem("operator", "John");
const temp = AsyncStorage.getItem("operator");
console.log(temp);
}
但是console.log(temp);
又说了undefined
!
为什么我不能使用 setItem
然后使用 getItem
获取数据?
Thanks in advance!
AsyncStorage 是异步 :-)。提交的值在其返回的承诺解决之前不可用。作为这种不便的交换,它不会在写入过程中阻塞您的 JavaScript 线程。
如果你尝试:
AsyncStorage.setItem("operator", "John").then(
() => AsyncStorage.getItem("operator")
.then((result)=>console.log(result))
)
你应该得到你所期望的。 (这也可以使用 async/await 来完成,如 AsyncStorage docs 所示)。
你并没有真正向我们展示你是如何将道具输入你的应用程序的,但是如果你在 then
上更新值时用 isLoggedIn
更新 <App>
的道具,您的组件应相应更新。
我正在尝试进行身份验证,因此我的 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
中我将更改 operator
到用户登录后类似 "john" 的内容。
但由于某种原因它返回了 <Router />
(考虑到 isLoggedIn
在逻辑上一定是错误的但是...)
我也尝试在该部分中 setItem 进行测试,但再次没有结果:
componentWillMount() {
AsyncStorage.setItem("operator", "John");
const temp = AsyncStorage.getItem("operator");
console.log(temp);
}
但是console.log(temp);
又说了undefined
!
为什么我不能使用 setItem
然后使用 getItem
获取数据?
Thanks in advance!
AsyncStorage 是异步 :-)。提交的值在其返回的承诺解决之前不可用。作为这种不便的交换,它不会在写入过程中阻塞您的 JavaScript 线程。
如果你尝试:
AsyncStorage.setItem("operator", "John").then(
() => AsyncStorage.getItem("operator")
.then((result)=>console.log(result))
)
你应该得到你所期望的。 (这也可以使用 async/await 来完成,如 AsyncStorage docs 所示)。
你并没有真正向我们展示你是如何将道具输入你的应用程序的,但是如果你在 then
上更新值时用 isLoggedIn
更新 <App>
的道具,您的组件应相应更新。