AsyncStorage 不保存更改状态 - React Native

AsyncStorage don't save the change state - React Native

我遵循了有关 AsyncStorage 的文档示例:

React Native - AsyncStorage docs

。所以,我实现了我的代码:

var STORAGE_KEY = '@AsyncStorageExample:key';

我用这个函数定义我的class:

我有一个初始状态:

state={
  defineValor: 0,
};

componentDidMount函数和_loadInitialState:

componentDidMount() {
  this._loadInitialState().done();
};

_loadInitialState = async () => {
  try {
    var value = await AsyncStorage.getItem(STORAGE_KEY);
    if (value !== null){
      this.setState({defineValor: value});
      alert('Recovered selection from disk: ' + value);
    } else {
      alert('Initialized with no selection on disk.');
    }
  } catch (error) {
    alert('AsyncStorage error: ' + error.message);
  }
};

所以我做了一个函数来使用 AsyncStorage 更改状态,在文档中也是如此:

changeState = () => {
  this.setState ({
    defineValor: 1
  });
  try {
    AsyncStorage.setItem(STORAGE_KEY, this.state.defineValor);
    alert('Saved selection to disk: ' + this.state.defineValor);
  } catch (error) {
    alert('AsyncStorage error: ' + error.message);
  }
};

所以,当我打开应用程序时,所有过程 运行、警报 "Initialized with no selection on disk" 以及当我调用我的函数 changeState 时,他都会警报 "Saved selection to disk: 1"。但是当我关闭 de 应用程序并重新打开时,状态没有保存,并且他处于警报状态 "Initialized with no selection on disk."。我做错了什么?

setState 有一个回调在该回调中执行 AsyncStorage.setItem。 此外,AsyncStorage 仅接受 string 作为 value

this.setState({ defineValor: string }, () => {
  try {
    AsyncStorage.setItem(STORAGE_KEY, this.state.defineValor);
    alert('Saved selection to disk: ' + this.state.defineValor);
  } catch (error) {
    alert('AsyncStorage error: ' + error.message);
  }
});