承诺然后在thunk发送中返回undefined?

时间:2018-05-03 16:18:52

标签: javascript reactjs ecmascript-6 redux

我想将用户重定向到某个地方,如果他/她已登录,我可以使用Promise来执行此操作,但我的redux thunk async并不会将响应中的任何内容返回给组件。

export function loginUser(email,password){
  return dispatch=>{

    return axios.post('auth/login', {email,password})
      .then(res=>{
        if(res.status===200 && res.data.status===1){

          //things are working here
          dispatch({
            type: AUTH_SUCCESS,
            payload: res.data.data
          })
        }
      })
      .catch(res => { 
        dispatch(errorMsg(res.data.msg))
      })
  }
}

在我的组件中我做了

componentDidMount() {
  this.props.loginUser('username', 'pass')
  .then(resp => {
    console.log(resp) //this is undefined?!
  })
}

我试过这个

return dispatch({
  type: AUTH_SUCCESS,
  payload: res.data.data
})

它也不起作用。

除了使用then之外,我还能做些什么来将用户重定向到登录页面?

2 个答案:

答案 0 :(得分:2)

您还必须从Promise的.then().catch()回调中返回:

export function loginUser(email,password){
  return dispatch=>{

    return axios.post('auth/login', {email,password})
      .then(res=>{
        if(res.status===200 && res.data.status===1){

          //things are working here
          dispatch({
            type: AUTH_SUCCESS,
            payload: res.data.data
          })

          // return when success
          return {
            type: AUTH_SUCCESS,
            payload: res.data.data
          }
        }

        // return if failed, you can also return Promise.reject to invoke the .catch
        return "something" 
      })
      .catch(res => { 
        dispatch(errorMsg(res.data.msg))

        // return error message
        return res.data.msg;
      })
  }
}

答案 1 :(得分:0)

您可以返回

之类的承诺
textbox.Document.Blocks.Clear();
相关问题