React Native中的onPress菜单时如何保存价值?

时间:2019-02-04 10:04:27

标签: reactjs react-native

我是本机新手,我正在测试如何在单击按钮时节省价值,这是带有两个按钮的菜单

<MenuItem onPress={this.hideMenu}>Menu item 1</MenuItem>
<MenuItem onPress={this.printValue}>Menu item 2</MenuItem>

以下几行是我的主要活动

_storeData = async () => {
  try {
    await AsyncStorage.setItem('test', 'I like to save it.');
  } catch (error) {
    // Error saving data
  }
};

_retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('test');
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
  } catch (error) {
    // Error retrieving data
  }
};

hideMenu = () => {
  this._storeData();
  this._menu.hide();
};

printValue = () => {
    this._retrieveData();
    alert(this._retrieveData.value);
}

上面的代码不起作用,有人知道该怎么做吗?

1 个答案:

答案 0 :(得分:0)

您已经做了很好的尝试,但是却缺少一些东西。

您应该在函数调用之前放置await,因为它们是异步函数。另外,您不会从_retrieveData函数返回任何内容。

  1. 在正确的位置添加await
  2. value函数返回_retrieveData,您可能希望根据返回的内容返回不同的值。您可以重构它以使用诺言。

这是您的代码及其更新。

_retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('test');
    if (value !== null) {
      // We have data!!
      console.log(value);
      return value; // <- return the value that you have found
    }
     // you may wish to return something if no value is found
  } catch (error) {
    // Error retrieving data
    // you may wish to return something if an error occurs
  }
};

hideMenu = () => {
  await this._storeData();  // <- add await here
  this._menu.hide();
};

printValue = () => {
    let value = await this._retrieveData(); // <- add await and capture the returned value
    alert(value);
}