加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-native – 如何使用AsyncStorage在数组中存储记录

发布时间:2020-12-15 20:51:07 所属栏目:百科 来源:网络整理
导读:刚才我开始使用AsyncStorage.我尝试存储输入文本值,如下所示: class Sample extends React.Component{ constructor(props){ super(props); this.state = { Name:' ',}; }componentDidMount() { AsyncStorage.getItem("Name").then((value) ={ this.setState
刚才我开始使用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>
   )
}

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

Stringify数组

使用JSON.stringify和JSON.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!'));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读