我从安全存储中获取了一些userData,并尝试将其放入this.state,然后在单独的文本字段中显示项目。例如:
名字:Mark
姓:哈哈
当我显示this.state.UserData时,它会打印所有数组数据,但是我只想访问其中的一个子数据。我该怎么办?
constructor(props){
super(props)
this.state={
UserData: ''
}
}
componentWillMount() {
SecureStore.getItemAsync('userData')
.then((data) => {
this.setState({ UserData: data })
});
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>
{this.state.UserData['FirstName']}<-- not doing anything
</Text>
</View>
);
}
安全商店设置功能:
userLogin = () =>{
const {Email, passWord} = this.state;
if(Email !== "" && passWord !== ""){
fetch('', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Max-Age': '3600',
'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
},
body: JSON.stringify({
action: 'login',
email: Email,
password: passWord
})
})
.then((response) => response.json())
.then((responseJson) => {
//console.log(responseJson);
if(responseJson !== "" && responseJson !== '0'){
Alert.alert(
'Succes',
'ingelogd!',
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{ cancelable: false }
)
try {
SecureStore.setItemAsync('userData', JSON.stringify(responseJson));
} catch (error) {
alert('Er ging iets mis, probeer het later opnieuw ' . error);
}
}
}
答案 0 :(得分:2)
您遇到问题的原因是因为SecureStore
仅保存字符串。您已经非常正确地使用JSON.stringify
将对象转换为字符串,以便可以保存它,但是您需要将其转换回对象。
您可以使用JSON.parse
将字符串转换回一个对象。
constructor(props){
super(props)
this.state={
UserData: {} // update this to an object
}
}
componentWillMount() {
SecureStore.getItemAsync('userData')
.then((data) => {
let UserData = JSON.parse(data) // you need to parse the string to json
console.log(UserData); // you probably want to check what you have gotten back
this.setState({ UserData: UserData }) // then save the object to state
});
}
现在,只要您的对象具有键Firstname
和Lastname
,您就应该能够像这样访问它们
this.state.UserData.Firstname
this.state.UserData.Lastname