如何使用 AsyncStorage 在数组中存储记录 [英] How to store records in an array using AsyncStorage
本文介绍了如何使用 AsyncStorage 在数组中存储记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚开始使用 AsyncStorage.我尝试像这样存储输入文本值:
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.
推荐答案
Stringify Array
使用 JSON.stringify 和 JSON.parse 通过 AsyncStorage<将数组存储为值/代码>.
Stringify Array
Use JSON.stringify and JSON.parse to store an array as a value via 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!'));
这篇关于如何使用 AsyncStorage 在数组中存储记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文