问题
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