【发布时间】:2019-08-02 09:04:53
【问题描述】:
我需要使用 AsyncStorage 存储来自屏幕的两个值,并将其存储为键值对的格式。我希望这些数据本地存储在移动设备中,然后在需要时从中检索。 我尝试检索单个数据,但无法处理多个数据。
import React, { Component } from 'react';
import { StyleSheet, AsyncStorage, TextInput, View, Alert, Button, Text, TouchableOpacity } from 'react-native';
class FormData extends Component {
constructor(props){
super(props)
this.state = {
// myKey: '',
key: '',
text1: '',
text2: '',
getValue: '',
infoValue:''
};
}
savefunction = () => {
let storedObject = {};
storedObject.textval1 = text1;
storedObject.textval2 = text2;
try {
AsyncStorage.setItem('allTextValue', JSON.stringify(storedObject));
} catch (error) {
}
}
getfunction = () => {
try {
AsyncStorage.getItem('allTextValue').then((infoValue) => {
let resObject = JSON.parse(infoValue);
let textval1 = resObject.text1
let textval2 = resObject.text2
}).done();
} catch (error) {
}
}
render (){
return(
<View style={styles.MainContainer}>
<Text style= {styles.TextComponentStyle}>User Form</Text>
<TextInput
placeholder="Enter User Email"
onChangeText={(value) => this.setState({ text1: value})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={(value) => this.setState({ text2: value})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<Button onPress={this.savefunction}
title="Save key" color="#2196F3" />
<Button onPress={this.getfunction}
title="Get key" color="#2196F3" />
<Text style={styles.text}> {this.state.getValue} </Text>
</View>
);
}
}
export default FormData;
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 10,
},
TextInputStyleClass: {
textAlign: 'center',
marginBottom: 7,
height: 40,
borderWidth: 1,
// Set border Hex Color Code Here.
borderColor: '#2196F3',
// Set border Radius.
borderRadius: 5 ,
},
text: {
fontSize: 20,
textAlign: 'center',
},
TextComponentStyle: {
fontSize: 20,
color: "#000",
textAlign: 'center',
marginBottom: 15
}
});
我希望多个数据通过键值对存储在地图中
【问题讨论】:
-
保存它的代码很好,它在 asyncStorage 中保存了一个具有 2 个值的对象。当您检索它并执行 JSON.parse 时,它会返回具有两个值的所需对象。有什么问题?
-
我无法得到想要的结果。而且我希望它像键值对一样
-
什么意思?您想如何访问该值? resObject.textval1 将返回您想要的字符串。现在我看起来你正在做未定义的 resObject.text1