【问题标题】:Values are not stored in array AsyncStorage react native值不存储在数组 AsyncStorage 反应原生
【发布时间】:2018-01-31 04:51:36
【问题描述】:

我正在尝试将值作为数组存储在 AsyncStorage 中,但是当我尝试从数组中获取值时,值并没有保存在那里并且什么也得不到。任何帮助将不胜感激。提前谢谢你,这是我的代码:

let searchString = this.state.inputValue

AsyncStorage.getItem('searches', (res) => {
  var searches
  if (res === null) {
    searches = []
  }else {
    searches = JSON.parse(res)
  }
  searches.push({
      searchString: searchString
  })
  AsyncStorage.setItem('searches', JSON.stringify(searches), (res) => {
      console.log('====FirstPage====setItem==async==='+res)
  })
}); 

//从异步存储中获取值:

AsyncStorage.getItem('searches', (res) => {console.log('===res==='+res)})

【问题讨论】:

  • 你能显示在 AsyncStorage 中保存/存储值的代码吗?
  • 你使用了 AsyncStorage.getItem() 吗?
  • 我已经更新了我的问题。

标签: arrays react-native asyncstorage


【解决方案1】:

请试试这个

AsyncStorage.getItem("searches").then((value) => {
    this.setState({"searches": value});
}).done();

另见 https://www.thepolyglotdeveloper.com/2015/09/saving-data-in-your-react-native-mobile-application/

【讨论】:

    【解决方案2】:

    您可以按以下方式存储数据:

    AsyncStorage.setItem('searches', JSON.stringify(searchString));
    

    为了获取/获取,您可以使用以下方法:

    AsyncStorage.getItem('searches', (err, result) => { // err indicating the error
      console.log("Storage Data(String):", result); // print is string format
      console.log("Storage Data(Object):", JSON.parse(result)); // print is json format
    })
    

    【讨论】:

    • 输入值现在保存在 asyncstorage 中,但在第二次输入时,它会覆盖第一个值,而不是像数组一样附加值。
    • 你的意思是你正在做 AsyncStorage.setItem 多次“搜索”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多