繁体   English   中英

承诺然后在重调度中返回未定义?

[英]Promise then return undefined in thunk dispatch?

我想将用户重定向到某个已登录的地方,我可以使用Promise来做到这一点,但是我的redux thunk异步不会在响应中返回任何内容。

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,我还能做什么来将用户重定向到登录页面?

你必须从承诺的回报.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;
      })
  }
}

您可以像这样返回Promise

export function loginUser(email,password){
  return dispatch=>{
   return new Promise((resolve, reject) => {
      axios.post('auth/login', {email,password})
      .then(res=>{
        if(res.status===200 && res.data.status===1){
          resolve(res.data.data)
          //things are working here
          dispatch({
            type: AUTH_SUCCESS,
            payload: res.data.data
          })
        }
        reject(res.status)
      })
      .catch(res => { 
        reject(res);
        dispatch(errorMsg(res.data.msg))
      })
    })
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM