我是本机反应的新手,我正在尝试实现用户登录(仅用于测试,未连接到任何服务器)。 我可以将数据存储在Asyncstorage中,但是当我刷新页面时,所有数据都会被删除。
这是我的代码:
export default class TEST extends Component{
componentWillMount(){
this.state = {
username:''
}
}
async _SaveInState(value) {
try {
await AsyncStorage.setItem('@MySuperStore:key', value);
console.log('getting ok')
}catch (error) {
console.log('error in Gett'+error)
}
}
async _SotreInStorage(){
try {
let value = await AsyncStorage.getItem('@MySuperStore:key')
this.setState({username:value});
console.log('saving ok')
}catch (error) {
console.log('error in saving'+error)
}
}
render(){
return(
<View>
<TextInput onChangeText={(value) => this._SaveInState(value)}
defaultValue={this.state.username}/>
<TouchableOpacity onPress={() => this._SotreInStorage()}>
<Text>ثبت نام</Text>
</TouchableOpacity>
<Text>{this.state.username}</Text>
</View>
)
}
答案 0 :(得分:0)
constructor(props) {
super(props);
this.state = {
username: ''
}
}
async storeUserName(username) {
try {
await AsyncStorage.setItem('username', username);
console.log("Data saved successfully");
// Rest of your code
} catch (error) {
console.log("Error while storing the username");
}
}
async retrieveUserName() {
try {
const username = await AsyncStorage.getItem('username');
if (token !== null) {
console.log("User Name",username );
return username;
}
} catch (error) {
console.log("Error while storing the token");
}
}
componentDidMount() {
this.retrieveUserName()
.then((username)=> {
if(username) this.setState({username: username})
})
}
render(){
return(
<View>
<TextInput
onChangeText={(value) => this.setState({username: value})}
defaultValue={this.state.username}/>
<TouchableOpacity onPress={() => this.storeUserName()}>
<Text>ثبت نام</Text>
</TouchableOpacity>
<Text>{this.state.username}</Text>
</View>
)
}