问题描述
我正在尝试使用异步存储来存储两个作为对象存储的文本输入值,并将其传递到不同的视图,在那里它们将在按下按钮时显示.
I'm trying to use Async storage to store two Text Input values stored as an object and pass it to a different view where they'll be displayed on a button press.
正如其他 StackOverflow 帖子中提到的,我使用 JSON.parse 和 JSON.stringify 将对象作为 JSON 数据传递,但仍然出于某种原因,我收到错误 JSON Parse Error: Unexpected Identifier "Undefined"(React Native)
As mentioned in other StackOverflow posts I've used JSON.parse and JSON.stringify to pass the object as JSON data, still for some reason I;m getting the error JSON Parse Error: Unexpected Identifier "Undefined"(React Native)
class AddData extends React.Component {
constructor(props) {
super(props);
this.state = {
text1: '' ,
text2: ''
};
}
render() {
function BtnPress() {
alert('Hi')
}
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
<TextInput
style={{height: 40,width:200}}
onChangeText={(text1) => this.setState({input1: text1})}
/>
<TextInput
style={{height: 40,width:200}}
onChangeText={(text2) => this.setState({input2: text2})}
/>
<Button
onPress={() => {
AsyncStorage.setItem('user', JSON.stringify({
name:'Rohit',
email: 'rohitgird12gmail.com'
}));
this.props.navigation.navigate('Home', {});
}}
title="Submit"
/>
</View>
);
}
}
查看以显示数据
class DetailsScreen extends React.Component {
displayName = async ()=> {
try {
const myArray = await AsyncStorage.getItem('user');
if (myArray !== null) {
alert(JSON.parse(myArray.name));
}
} catch (error) {
alert(error)
}
}
render() {
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
<Button
onPress={this.displayName}
title="Get Data"
/>
</View>
);
}
}
推荐答案
看起来 const myArray = await AsyncStorage.getItem('user');
正在返回 undefined
而你只为 null
辩护,这在这里是不够的.
It looks like const myArray = await AsyncStorage.getItem('user');
is returning undefined
while you defended yourself from null
only, which is not sufficient here.
另一个可能的问题是:JSON.parse(myArray.name)
.你确定它不应该是 JSON.parse(myArray).name
?
Antoher possible problem lies here : JSON.parse(myArray.name)
. Are you sure it's not supposed to be JSON.parse(myArray).name
?
这篇关于JSON 解析错误:意外的标识符“未定义"(React Native)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!