ReactJS + Redux:在进入下一步之前如何等待调度完成?

6 javascript reactjs react-jsx redux react-redux

在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)
      })
    }
Run Code Online (Sandbox Code Playgroud)

先感谢您

Don*_*mmy -1

将您的window.location.href ='http://localhost:3005/#/Home'内容放入您的订阅处理程序中。并确保您订阅了该活动:

constructor(props, children)
{
    TheStore.subscribe( this.listenForDispatch.bind( this ) );
}

listenForDispatch()
{
    //Check the state is what you want
    if ( TheStore.getState().someProp == "somevalue" )
    {
        //Call it here!
        window.location.href ='http://localhost:3005/#/Home'
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:在代码中开始使用 Redux 之前,您需要阅读他们的文档和教程subscribe是 Redux 使用方式的基本部分之一。