使用AsyncStorage实例化持久性应用程序状态

我试图创build一个对象,将作为我的应用程序的持久状态。 这意味着应用程序启动后第一次引用状态,它需要从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 } })(); 

现在,当我尝试并使用它时,这将返回承诺。 有什么办法从承诺中提取我的对象的价值,或者是一个更好的模式来完成我所要做的事情? 也许我必须在启动时初始化状态。

好的,我有一个可行的解决scheme。 本质上,我延迟了应用程序的初始化,直到通过AsyncStorage加载状态。 这是必要的,因为它是告诉应用程序是否在login屏幕上启动的状态。 在我的根文件中:

  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 } } } 

在我的国家class上:

 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) } } } 

现在,我可以在我的应用程序中安全地引用状态variables,因为初始化发生在别的之前。 据我所知,这是做这件事最好的(唯一的)办法。 如果不是这样,让我知道,因为这是非常丑陋的。