将回调传递给 redux 异步操作是否被认为是一种好习惯? [英] is it considered good practice to pass callBacks to redux async action?

查看:30
本文介绍了将回调传递给 redux 异步操作是否被认为是一种好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为成功/错误响应显示不同的通知栏,我将两个回调传递给我的反应组件中的 redux 异步操作,如下所示:

I want to show different notification bars for success/error responses, I pass two callBacks to an redux async action in my react component like this:

<Button
  onClick={e => this.props.actions.asyncAction(item, this.showSuccessBar, this.showErrorBar)}
/>

其中 asyncAction 看起来像这样:

where asyncAction looks like this:

export function asyncAction(item, successCallback, errorCallback) {
  return (dispatch, getState) => {
    dispatch(requestItem(item));
    return fetch("api.some_url/items/item")
      .then(response => response.json())
      .then(json => {
        if (json.success) {
          dispatch(receivePostsSuccess(reddit, json));
          successCallback();
        } else {
          dispatch(receivePostsFail(reddit, json));
          errorCallback();
        }
      });
    }
  };
}

这是否被认为违反了模式?换句话说,通知栏是否应该根据状态变化而不是回调打开?

Is this considered against the pattern? in other words, Should Notification Bars open according to the state change instead of callBacks?

推荐答案

模式本身就很好.如果这是组件本地的通知,请随意避免通过 Redux 连接它.

The pattern is fine per se. If this is a notification local to the component, feel free to avoid wiring it through Redux.

上述回调完全没有必要因为您已经在返回承诺.只需等待其完成即可.

That said callbacks are completely unnecessary because you are already returning the promise. Just wait for its completion.

this.props.dispatch(asyncAction(item)).then(onSuccess, onFailure);

但是,如果您有许多带有此类通知栏的组件,最好有一个 reducer 来保持当前通知并对操作做出反应.

However if you have many components with such notification bars, it's better to have a reducer keeping the current notification and reacting to actions.

这篇关于将回调传递给 redux 异步操作是否被认为是一种好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆