目前正在为我的反应应用程序使用AWS Cognito SDK . 目前,在调用API时,我使用ComponentWillMount运行会话检查
componentWillMount() {
if (!this.props.authenticated) {
this.props.history.push('/auth/login');
} else {
getUserFromLocalStorage()
.then(data => {
console.log('getUserFromLocalStorage');
this.props.setUserToReduxState(data);
console.log(
'user sucess retrieved from local storage and usersettoreduxstate: ',
data
)
.then(console.log('after local test'))
})
.catch(() => {
logoutUserFromReduxState();
});
}
}
在componentDidMount中,我使用本地存储中的JWT令牌调用API
componentDidMount() {
// calls API with localStage.jwtToken
this.loadData();
}
这大部分时间都可以工作,但是当令牌过期时,JWT会被刷新,但是当最初调用API时,它会被旧的JWT调用 . 我可以看到新的JWT在redux中被刷新,但是在调用API之前它会被刷新 .
是否有任何建议要确保在每次API调用之前,在API调用中使用之前,令牌会在redux中刷新和更新?
1 回答
这可能是由于javascript的异步性质造成的 . 只需确保
this.lodaData()
等待刷新令牌 .例如,
componentWillMount
运行身份验证部分,componentDidMount
不会等待身份验证功能在进行API
调用之前完成运行 .现在无法通过立即分离身份验证部分和
API
来完成此操作,但您可以将它们全部放在componentWillMount
或componentDidMount
中的所有事件中,并确保在所有身份验证之后调用API调用 . 像下面的东西