使用ReactJS刷新API中的令牌



早上好,我有一个REST API,它需要一个令牌来访问它。我已经用Reactjs生成了令牌,但现在我需要它不时刷新。为此,我需要以某种方式存储令牌,这样我就可以再次获取API。我尝试使用本地存储,但没有成功。有什么帮助吗?

constructor(props) {
super(props);
this.state = {
models: [],
isLoaded: false
};
}
componentDidMount() {
const email = myEmail;
const pass = myPass;
const url = url;
fetch(url + '/api-token-auth/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}, body: JSON.stringify({
email: email,
password: pass,
})
})/*, fetch(url + "/api-token-refresh/", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}, body: JSON.stringify({
token: token
})
})*/
// <-- code for refreshing token, working on it
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
let token = this.state.token;
console.log('var token: ', token);
localStorage.setItem('token', token);
})
.catch(error => console.error(error));
const token = localStorage.getItem('token');
console.log('localStorage w token: ', token);
}`

据我所知,错误在第二个promise处理程序中。this.setState({}(是一个异步函数,这意味着在执行.then函数中的其他指令后设置状态。

.then(json => {
this.setState({
isLoaded: true,
token: json
});
/*the above function is executed after below statements are executed beecause the nature of this.setState is asynchronous*/
/*and that is why you must be getting an old or garbage value from this.state.token then in localStorage */
let token = this.state.token;
console.log('var token: ', token);
localStorage.setItem('token', token);
})

要解决此问题:您可以在this.setState中提供回调函数,该函数只有在设置了状态后才执行!万岁!像这样:

.then(json => {
this.setState({ isLoaded: true, token: json }, () => {
//this is the callback function
//you should do tasks which depend on new state here
let token = this.state.token;
console.log('var token: ', token);
localStorage.setItem('token', token);
});
})

dbvt10在上面的评论中也指出了同样的事情。

您可以在Medium.com的这篇精彩文章中阅读更多关于setState回调函数的信息。^_^

这是我的解决方案,我需要将令牌存储为具有JSON.stringify的字符串,然后,当我需要再次使用它时,使用JSON.parse

componentDidMount() {
const email = myEmail;
const pass = myPass;
const url = url;
fetch(url + '/api-token-auth/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}, body: JSON.stringify({
email: email,
password: pass,
})
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
isLoaded: true,
token: json
}, () => {
let tokenJson = JSON.stringify(json);
localStorage.setItem('token', tokenJson);
});
}).catch(error => console.error('erro:' + error));

fetch(url + '/api-token-refresh/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}, body: (localStorage.getItem('token'))
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
isLoaded: true,
token: json
}, () => {
let tokenJson = JSON.stringify(json);
localStorage.setItem('token', tokenJson);
});
})
}

最新更新