首页 > 解决方案 > 当onPress菜单反应原生时如何保存价值?

问题描述

我是 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);
}

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

标签: reactjsreact-native

解决方案


你做了一个很好的尝试,但你错过了一些事情。

你应该await在你的函数调用前面,因为它们是异步函数。此外,您没有从您的_retrieveData函数中返回任何内容。

  1. await在正确的地方添加
  2. 返回valuefrom_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);
}

推荐阅读