【发布时间】:2017-02-21 18:44:48
【问题描述】:
在 ReactJS + Redux 项目中,我有一个方法可以发出 API 请求。如果成功,我想分派另一个动作创建者并等待它完成。然后当它完成时,进入下一步。
目前,下面的代码在进行另一个 API 调用时执行调度,但即使在通过调度更新状态之前,它也会立即执行window.location.href ='http://localhost:3005/#/Home',然后调度完成。
那么我如何才能等到dispatch(actions.updateUserInfo(userInfo.username)) 完成后再执行下一行代码window.location.href ='http://localhost:3005/#/Home'?
这里是动作创建者:
loggingIn(userInfo) {
var userInfoBody = {
'username': `${userInfo.username}`,
'password': `${userInfo.password}`
}
var configuration = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userInfoBody)
}
return function(dispatch) {
fetch('https://backendserver.com:8080/creds', configuration)
.then(response => response.json())
.then(response => {
//Would like to finish this dispatch completely before start executing window.location.href ='http://localhost:3005/#/Home'
dispatch(actions.updateUserInfo(userInfo.username))
window.location.href ='http://localhost:3005/#/Home'
})
.catch((error) => {
console.log("Error: ", error)
})
}
提前谢谢你
【问题讨论】:
标签: javascript reactjs redux react-jsx react-redux