Redux异步actioncreator无法识别

时间:2018-09-04 12:50:56

标签: react-native redux redux-thunk

我需要在还原操作上使用.then(),以下操作有什么问题?

export const userLogin = (username, password) => {
  return dispatch => {
    axios.post(`${TT_API_BASE}/Access/Login`, { username: username, password: password, applicationId: 2 }, {
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': 'Basic ' + auth,
      }
    })
      .then(response => {
        dispatch({
          type: LOGIN,
          payload: response.data
        })
      })
      .catch(err => {
        console.log(err)
        dispatch({
          type: LOGIN_FAILED
        })
      })
  }
}

然后在这样的组件中调用

  handlePress() {
    this.props.userLogin(this.state.username, this.state.password)
      .then(() => {
        this.props.navigation.navigate('SelectInstance')
      })
  }

将显示随后未定义的错误消息。我在做什么错了?

2 个答案:

答案 0 :(得分:0)

当您执行dispatch(someThunkActionCreator())时,dispatch的返回值就是您的thunk函数返回的值。因此,仅当thunk函数返回promise时,您才能执行dispatch().then()

您的thunk正在进行AJAX调用,但实际上未返回诺言,因此实际上返回了undefined。在return前面放置axios.post()语句将返回该承诺并解决问题。

答案 1 :(得分:0)

解决了这个问题

export const userLogin = (username, password) => {
  return async dispatch => {
    const onSuccess = data => {
      dispatch({
        type: LOGIN,
        payload: data
      })
    }
    const onError = err => {
      dispatch({
        type: LOGIN_FAILED
      })
    }
    try {
      const req = await axios.post(`${TT_API_BASE}/Access/Login`, { username: username, password: password, applicationId: 2 }, {
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          'Authorization': 'Basic ' + auth,
        }
      })
      return onSuccess(req.data)
    }
    catch (err) {
      return onError(err)
    }
  }
}