如何从React Redux中的ActionCreator返回一个承诺

时间:2016-08-22 02:58:05

标签: reactjs redux react-redux

我有以下处理程序调度两个动作......

 _onPress = () => {
    let { request,userId} = this.props;
    this.props.dispatch(acceptRequest(request.id,userId))
    this.props.dispatch(navigatePop());
 }

我想要的是以下内容......

 _onPress = () => {
    let { request,userId} = this.props;
    this.props.dispatch(acceptRequest(request.id,userId))
      .then(this.props.dispatch(navigatePop()))
 }

我的ActionCreator看起来像这样......

 export function acceptRequest(requestId,fulfilledBy){
   return dispatch => {
     fulfillments.create(requestId,fulfilledBy)
       .then(response => response.json())
       .then(fulfillment => {
         dispatch(_acceptRequestSuccess(fulfillment))
       })
       .catch(err => {
         console.log(err);
         dispatch(_acceptRequestError(error))
       })
   }
 }

我知道他们有许多人们建议的中间件,但我不知道 看看它们中的任何一个是否适合这种情况,除非我完成了某些事情 不正确。

在我的特殊情况下,如果第一个是,我只想发送seond动作 成功,但我不想从动作创建者那里做到这一点,因为那时候 它不太可重复使用。

1 个答案:

答案 0 :(得分:0)

好的,所以我误解了你,你应该提到你正在使用redux-thunk。

我不认为redux行动应该返回一个承诺,我认为你应该在组件中做所有事情,然后玩这个承诺,如下:

_onPress = () => {
    let { request,userId} = this.props;

    fulfillments.create(requestId,fulfilledBy)
       .then(response => response.json())
       .then(fulfillment => {
            this.props.dispatch(_acceptRequestSuccess(fulfillment))
       })
       .then(() => {
            this.props.dispatch(navigatePop());
       })
       .catch(err => {
         console.log(err);
         this.props.dispatch(_acceptRequestError(error))
       })
 }

但是如果你仍然想要返回一个承诺,你可以让行动中的函数返回承诺:

export function acceptRequest(requestId,fulfilledBy){
   return dispatch => {
     return fulfillments.create(requestId,fulfilledBy)
       .then(response => response.json())
       .then(fulfillment => {
         dispatch(_acceptRequestSuccess(fulfillment))
       })
       .catch(err => {
         console.log(err);
         dispatch(_acceptRequestError(error))
       })
   }
 }
相关问题