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

Instantiate persistent app state with AsyncStorage

本文关键字:应用 程序状态 AsyncStorage 实例化 使用      更新时间:2024-04-24

我正在尝试创建一个对象,作为我的应用程序的持久状态。这意味着应用程序启动后第一次引用状态时,需要从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中的变量,因为初始化发生在其他任何事情之前。据我所知,这是最好的(唯一的)方法。如果不是这样的话,请告诉我,因为这太难看了。