使用AsyncStorage实例化持久应用程序状态
Instantiate persistent app state with AsyncStorage
我正在尝试创建一个对象,作为我的应用程序的持久状态。这意味着应用程序启动后第一次引用状态时,需要从AsyncStorage加载状态对象。到目前为止,我得到的是:
var instance = null;
var State = {
user: "bob",
update(newState) {
Object.assign(instance, newState);
AsyncStorage.setItem('appState', JSON.stringify(instance)).then(() => {
AsyncStorage.getItem('appState', (err, result) => {
console.log(result)
})
})
}
}
module.exports = (() => {
if (!instance) {
return AsyncStorage.getItem('appState').then((value) => {
if (value) {
instance = value
console.log("assigning saved state")
} else {
instance = State
console.log("assigning fresh state")
AsyncStorage.setItem('appState', JSON.stringify(instance))
}
return instance
})
} else {
console.log("using existing state")
return instance
}
})();
现在,当我尝试使用它时,它会返回promise。有没有办法从promise中提取我的对象值,或者有更好的模式来完成我要做的事情?也许我只需要在启动时初始化State。
好吧,我有一个可行的解决方案。从本质上讲,我推迟了应用程序的初始化,直到通过AsyncStorage加载状态。这是必要的,因为这是告诉应用程序是否在登录屏幕启动的状态。在我的根文件中:
constructor(props) {
super(props);
this.state = {
stateLoaded: false
}
State.initialize().then(() => {
this.setState({stateLoaded: true})
})
}
render() {
if (this.state.stateLoaded) {
return (
// Your startup code
);
} else {
return (
// Your loading screen code
}
}
}
在我的州立大学课堂上:
initialize() {
if (!this.initialized) {
return AsyncStorage.getItem('appState').then(value=>JSON.parse(value))
.then((value) => {
if (value) {
Object.assign(this, value)
console.log("assigning saved state")
} else {
console.log("assigning fresh state")
AsyncStorage.setItem('appState', JSON.stringify(this))
}
this.intialized = true
return this
})
} else {
return promise.resolve(this)
}
}
}
现在,我可以在整个应用程序中安全地引用State
中的变量,因为初始化发生在其他任何事情之前。据我所知,这是最好的(唯一的)方法。如果不是这样的话,请告诉我,因为这太难看了。
相关文章:
- 在mvc应用程序中,在回发时保留最初隐藏的文本框的隐藏或可见状态
- 使用应用程序状态js和视图在angular js url上传递两个参数
- 来自应用程序状态的Jquery数据表源
- 检测Ionic中特定的应用程序状态变化
- 使用AsyncStorage实例化持久应用程序状态
- 如何在类似Om的不可变应用程序状态下对关系数据进行建模
- 在节点.js中保存应用程序状态
- 在 React + Flux 中从子项更新应用程序状态
- 输入模式应用程序状态,直到下次使用 Jquery 单击
- Rails API-移动应用程序状态文本错误
- 什么'是在AngularJS中处理应用程序状态和事件广播的最佳实践
- React.js:从独立组件访问整个应用程序状态
- Backbone.js如何根据特定的应用程序状态定义一组自定义路由
- 使用基于应用程序状态/数据的UI路由器
- Ionic混合应用程序,在退出时保存应用程序状态/数据
- 在AJAX应用程序中保持web应用程序状态
- 在 react-redux 应用程序状态的数据结构中具有 didInvalidate 属性的目的是什么?
- 使用react路由器更改应用程序状态时出现问题
- React Redux-如何在应用程序状态中设置字段
- ExtJS 4 Web 应用程序状态管理