【发布时间】:2019-11-03 02:44:40
【问题描述】:
我不明白如何使 AsyncStorage 工作。 我使用 react-native-router-flux
基本上我有 3 页:
首页
export default class Authentication extends Component {
render() {
return (
..........
<TouchableOpacity
style ={[style.button, style.buttonOK]}
onPress={() => Actions.login() }>
<Text style={style.buttonTesto}>LOGIN</Text>
</TouchableOpacity>
<TouchableOpacity
style ={[style.button, style.buttonOK]}
onPress={() => Actions.signup() }>
<Text style={style.buttonTesto}>SIGNUP</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
登录
login() {
let ctrl = true;
......
if (ctrl) {
let formdata = new FormData();
const identity = {
AppName: {
Username: this.state.username,
Password: this.state.password
}
};
formdata.append("Identity", JSON.stringify(identity));
fetch(APILINK , {
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
body: formdata
})
.then(response => response.json())
.then(responseData => {
if (responseData.Error) {
.......
} else {
global.utente = new Utente(responseData);
Actions.homepageutente();
}
})
.catch(err => alert("err:" + err));
}
}
Utente
export default class Utente {
constructor(data) {
Utente.saveUtenteLoggato(data);
this._data = data;
....
);
}
get data() {
return this._data;
}
//there is a function for the signup there//
.......
static async saveUtenteLoggato(value) {
try {
await AsyncStorage.setItem("@UtenteLoggato", JSON.stringify(value));
} catch (error) {
console.log(error.message);
}
}
static async getUtenteLoggato() {
try {
return await AsyncStorage.getItem("@UtenteLoggato");
} catch (error) {
console.log(error.message);
return null;
}
}
static async clearUtenteLoggato() {
try {
global.utente = null;
await AsyncStorage.removeItem("@UtenteLoggato");
} catch (error) {
console.log(error.message);
return null;
}
}
}
所以在 Utente 中我创建了 Asyncstorage 功能,但我不明白当我在后台关闭应用程序(例如)以保持登录活动时我应该怎么做。目前,如果我返回应用程序,我应该再次登录。 我该如何解决?
编辑 起始页
class Starting extends Component {
constructor(props)
{
super(props)
this.state = {
loading: true
}
}
componentWillMount() {
Utente.getUtenteLoggato()
.then(dataUtenteLoggato => {
if (dataUtenteLoggato !== null) {
global.utente = new Utente(JSON.parse(dataUtenteLoggato));
} else {
Actions.authentication();
}
})
.catch(err => {
console.log(err);
})
.finally(() => {
this.setState({ loading: false });
});
}
render() {
return(
<View style={style.container}>
<Spinner visible={this.state.loading} textContent={"Loading..."} textStyle={{color: '#FFF'}} />
</View>
);
}
}
【问题讨论】: