如何使用 AsyncStorage 将记录存储在数组中

新手上路,请多包涵

刚才我开始使用 AsyncStorage。我尝试像这样存储输入文本值:

 class Sample extends React.Component{
  constructor(props){
    super(props);
     this.state = {
      Name:' ',
    };
  }
componentDidMount() {
    AsyncStorage.getItem("Name").then((value) =>{
      this.setState({"Name":value})
    }).done();
handleChange(e){
      AsyncStorage.setItem("Name", e.nativeEvent.text)
       this.setState({
         email: e.nativeEvent.text
       })
    }
  render(){
    return(
       <View>
        <TextInput
               style={styles.textContainer}
               value={this.state.Name}
               placeholder="Name"
               onChange={this.handleChange.bind(this)}/>
       </View>
   )
}

为此,它工作正常,但我想将记录添加到数组中,而不是每次都更改记录。我想将记录推送到一个数组中,并且需要在视图中显示总数组数据,(即)我还需要以前可用的数据。

原文由 Hussian Shaik 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 637
1 个回答

字符串化数组

使用 JSON.stringifyJSON.parse 通过 AsyncStorage 将数组存储为值。

存储/字符串化

const stringifiedArray = JSON.stringify(somearray)

恢复/解析

const restoredArray = JSON.parse(stringifiedArray)

AsyncStorage

  return AsyncStorage.getItem('somekey')
      .then(req => JSON.parse(req))
      .then(json => console.log(json))
      .catch(error => console.log('error!'));

const someArray = [1,2,3,4];
return AsyncStorage.setItem('somekey', JSON.stringify(someArray))
      .then(json => console.log('success!'))
      .catch(error => console.log('error!'));

原文由 purii 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题