我试图调度一个动作,并使用中间件来检查令牌是否已过期,以及是否已过期我正在生成新令牌。然后,我在api中使用这个新令牌。问题是代码异步流动。 api使用的是旧令牌,而不是生成的新令牌。请帮助我解决问题。 注意-中间件代码在index.js文件中
this.props.checkToken(oldToken) //action dispatched goes to middleware
apicall(window.sessionSTorage.getItem('token')) //api using token
const mapDispatchToProps = (dispatch) => {
return {
checkToken: (token) => dispatch (actionCreators.checkToken(token))
}
}
export default connect(null, mapDispatchToProps)(myComponent)
动作创建者-
export const checkToken = (token) => {
return {
type: actionTypes.checkToken,
token: token,
}}
中间件-
//Middleware code here
const logger = store => {
return next => {
return action => {
if (tokenExpired) {
fetch (url, {
method: 'POST',
body: JSON.stringify(refresh),
headers: {
'Content-Type': 'application/json',
}
})
.then ((response) => response.json())
.then ((findresponse) => {
window.sessionStorage.setItem('token', findresponse.token);
})
}
return next(action);
}
}}
答案 0 :(得分:0)
操作将返回承诺,因此您可以在成功完成承诺后执行<div className="outermost_div additional">
<div className="save_div">
<button className="button_div" onClick={ props.on_selected}Save</button>
<div className="divider" />
<button className="button_div" onClick={props.on_cancel}>
Cancel
</button>
</div>
</div>
apicall
或使用异步/等待
this.props.checkToken(oldToken).then(()=>apicall(window.sessionSTorage.getItem('token'))
答案 1 :(得分:0)
我认为您的问题有很多解决方案(编辑中间件或使用RXJS订阅或创建另一个中间件来处理令牌...),但是我认为这不是一个好习惯。这是因为我们不需要向checktoken
发送动作。
应该由request
中间件来完成,该中间件在每个请求之前或位置路径更改时运行。您的解决方案还会导致刷新令牌和用新请求重新调用现有请求的困难。