const ACCESS_TOKEN = 'auth_token';
var api = {
async removeToken(){
try {
await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken(ACCESS_TOKEN);
} catch (error) {
console.log("something went wrong remove token")
}
},
async storeToken(accessToken){
try {
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken(ACCESS_TOKEN);
} catch (error) {
console.log("something went wrong store token")
}
},
async getToken(){
try {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
var parsedToken = JSON.parse(token).auth_token;
console.log("getToken: " + parsedToken);
return parsedToken;
} catch (error) {
console.log("something went wrong gettoken")
return null;
}
},
getTasks(){
var url = "http://doit.unicrow.com/api/v1/tasks/";
return fetch(url, {
method: 'GET',
headers: {
'Authorization': "Token" + this.getToken()
}
}).then(response => response.json())
}
}
module.exports = api;
大家好,我正在做一个反应js的项目,我遇到了问题。在getTasks方法的上面代码片段中,我想调用从getToken方法返回的标记值。使用“this”我无法做到这一点。我该怎么做?提前谢谢。
答案 0 :(得分:1)
你可以使用州
来做到这一点维持本地状态为
{ 令牌:"" } 将令牌置于状态为
async getToken(){
try {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
var parsedToken = JSON.parse(token).auth_token;
console.log("getToken: " + parsedToken);
// return parsedToken;
this.setState({
token:parsedToken
})
} catch (error) {
console.log("something went wrong gettoken")
return null;
}
},
并在你的getTasks方法中从状态
访问它 getTasks(){
var url = "http://doit.unicrow.com/api/v1/tasks/";
return fetch(url, {
method: 'GET',
headers: {
'Authorization': "Token" + this.state.token
}
}).then(response => response.json())
}
}