【问题标题】:React Native - Array Objects to AsyncStorageReact Native - 数组对象到 AsyncStorage
【发布时间】:2018-06-16 18:27:08
【问题描述】:

只是一个简单的问题,我一直在尝试使用 AsyncStorage 列出项目,但我就是想不通。我曾经根据网上的一些博客尝试过一些尝试,但它不起作用。所以,我在这里遇到了,希望有人能帮助我。

这是我的代码:

  constructor(props) {
    super(props);
    this.state = {
        myKey: []
    }
  }

  async getKey() {
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:key');
      this.setState({myKey: value});
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

  async saveKey(value) {
    try {
      await AsyncStorage.setItem('@MySuperStore:key', value);
    } catch (error) {
      console.log("Error saving data" + error);
    }
  }

更新:

Warning_ScreenShot

    <TextInput
      style={styles.formInput}
      placeholder="Enter key you want to save!"  // This is the component where I think the warning came from. 
      value={this.state.myKey}
      onChangeText={(value) => this.saveKey(value)}
    />

【问题讨论】:

    标签: javascript android react-native asynchronous


    【解决方案1】:

    调用AsyncStorage.getItem('@MySuperStore:key') 得到的值是对象还是数组?如果它只是一个对象,您可能希望将其附加到您的 myKey 数组中。

    async getKey() {
      try {
        const value = await AsyncStorage.getItem('@MySuperStore:key');
        const myKey = [ ...this.state.myKey, value ];
        this.setState({ myKey });
        } catch (error) {
        console.log("Error retrieving data" + error);
      }
    }
    

    【讨论】:

    • 首先,先生,当我尝试键入第二个对象时,它只是一个对象......第二个对象将替换第一个对象。但是使用您的代码,有些只是警告。我会更新我的问题中的详细信息。
    • 你到底想在这里实现什么?您有一个输入,当用户在此处输入内容时,您想在 myKey 数组中添加该单个字符(因为它会在每次更改时更新,对吗?)?
    猜你喜欢
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2019-01-30
    相关资源
    最近更新 更多