【问题标题】:Redux async actioncreator not recognizing thenRedux async actioncreator 无法识别
【发布时间】:2018-09-04 12:50:55
【问题描述】:

我需要在 redux 操作上使用.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')
      })
  }

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

【问题讨论】:

    标签: react-native redux redux-thunk


    【解决方案1】:

    当您执行dispatch(someThunkActionCreator()) 时,dispatch 的返回值是您的 thunk 函数返回的值。所以,只有当 thunk 函数返回一个 Promise 时,你才能执行 dispatch().then()

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

    【讨论】:

    • 谢谢你的回答,但是没有解决它。
    【解决方案2】:

    这样做解决了:

    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)
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-19
      • 2020-12-20
      • 1970-01-01
      • 2020-08-28
      • 2019-01-14
      • 2020-10-20
      • 2021-07-08
      • 2018-03-28
      • 2019-08-31
      相关资源
      最近更新 更多