Javascript 将回调传递给 redux 异步操作是否被认为是一种好习惯?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33138045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:40:52  来源:igfitidea点击:

is it considered good practice to pass callBacks to redux async action?

javascriptreactjsredux

提问by naifen

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:

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

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

where asyncAction looks like this:

其中 asyncAction 看起来像这样:

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?

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

回答by Dan Abramov

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

模式本身很好。如果这是组件本地的通知,请随意避免通过 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);

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.

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

回答by Brigand

This would be bi-directional data flow, which breaks the first rule of flux.

这将是双向数据流,打破了流量的第一条规则。

回答by ykravv

I suggest having separated store named smth like NotificationStoreand build notifications infrastructure around it. You can use callbacks, but it's way to big problems in future.

我建议将名为 smth like 的商店分开NotificationStore并围绕它构建通知基础设施。您可以使用回调,但这是将来解决大问题的方法。