我是新的反应原生,我现在只是学习反应本机,我试图通过单击注册按钮存储来自TextInput的值并存储到AsyncStorage。我试图通过单击获取按钮来获取该值。我可以&# 39;从AsyncStorage.getItem获取值('值'),之后我认为数据存储在AsyncStorage.setItem中(' name',' value' )。有人看看这段代码并告诉我答案我犯了错误。
export default class AsyncStorageEample extends Component
{
constructor(props)
{
super(props)
this.state= { name:'', email:'',mobile:''}
this.onRegisterPress=this.onRegisterPress.bind(this)
this.onRetreive=this.onRetreive.bind(this)
}
onRegisterPress()
{
let name=this.state.name
let email=this.state.email
let mobile=this.state.mobile
AsyncStorage.setItem('name',name)
AsyncStorage.setItem('email',email)
AsyncStorage.setItem('mobile',mobile)
this.setState({name: name, email:email,mobile:mobile})
}
onRetreive()
{
var user;
user= AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))
Alert.alert('Name:'+user);
}
render() {
return (
<View style={styles.container}>
<View style={styles.Signupform}>
<Text style={styles.textStyle}> Name </Text>
<TextInput style={styles.tInRegister} onChangeText={(text)=> this.setState({name: text})} value = {this.state.name}/>
<Text style={styles.textStyle}> Email </Text>
<TextInput style={styles.tInRegister} onChangeText={(text)=> this.setState({email: text})} value= {this.state.email} />
<Text style={styles.textStyle}> Mobile </Text>
<TextInput style={styles.tInRegister} onChangeText={(text)=> this.setState({mobile: text})} vaue= {this.state.mobile} />
<Button
onPress={this.onRegisterPress.bind(this)}
title="Register"
color="#841584"
/>
<Button
style={styles.get}
onPress={this.onRetreive.bind(this)}
title="Get"
color="#841584"/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
tInRegister: {
fontSize: 16,
height: 40,
color: '#800080'
},
textStyle: {
fontSize: 16,
color: '#800080'
},
Signupform: {
width: 400,
height: 100,
justifyContent: 'center',
marginTop: 10,
marginLeft: 10,
marginRight: 10
},
get:
{
marginTop:20,
},
});
AppRegistry.registerComponent('AsyncStorageEample', () => AsyncStorageEample);
答案 0 :(得分:1)
AsyncStorage是一种异步操作。所以应该用&#39;异步 - 等待&#39;
尝试以下代码
async onRetreive() {
const user = await AsyncStorage.getItem('name');
Alert.alert('Name:'+user);
}