How to store records in an array using AsyncStorage

元气小坏坏 提交于 2021-02-17 18:59:28

问题


Just now I started using AsyncStorage. I tried storing input text value like this:

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>
   )
}

For this it is working correctly, but i want to add a record into an array instead of changing the record every time. I want to push the record into an array and need to display the total array data in the view, (i.e) I need previously avilable data also.


回答1:


Stringify Array

Use JSON.stringify and JSON.parse to store an array as a value via AsyncStorage.

Store / Stringify

const stringifiedArray = JSON.stringify(somearray)

Restore / Parse

const restoredArray = JSON.parse(stringifiedArray)

Usage with 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!'));



回答2:


for setting

     AsyncStorage.setItem('name', JSON.stringify(your array));

for getting

  AsyncStorage.getItem('name', (error, result) => {
  this.setState({ name: JSON.parse(result) }, function () {   });});


来源:https://stackoverflow.com/questions/34651516/how-to-store-records-in-an-array-using-asyncstorage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!