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

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

问题描述

我想显示成功/错误响应的不同通知栏,
我将两个callBacks传递给我的react组件中的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();
        }
      });
    }
  };
}

这是否与模式有关?
换句话说,应该根据状态变化而不是callBacks打开通知栏吗?

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.

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

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