向Redux Reducer添加回调 [英] Adding a callback to a Redux Reducer

查看:70
本文介绍了向Redux Reducer添加回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

action.data中添加回调时,是否会出现任何错误/反模式错误(就' thinking-in-react / redux '而言) 通过了一项操作?

Would there be anything wrong/anti-pattern-ish (in terms of 'thinking-in-react/redux') in added a callback to the action.data passed into an action?

// reducer
ACTION_FOR_REDUCER() {
  var x = 123
  if ( action.data.callback ) action.data.callback( x )
  return {
    something: action.data.somedata
  }
},

然后在稍后调用该操作时在App中访问该数据(也许在容器中)

Then accessing that data later in the App when the action is called (in an container perhaps)

// later in the app
this.props.dispatch(changeSomething({
  somedata: somedata,
  callback: (x) => { console.log(x) }
}))    


推荐答案

想法没错,实现是。

不是添加回调,而是返回行动的承诺(您将需要 redux-thunk 中间件或一些中间件

Instead of adding a callback, return a promise from the action (you will need redux-thunk middleware or some similar alternative).

然后您可以简单地做到:

Then you can simply do:

dispatch(myAction).then(callback);

当然,您也可以在回调中简单地分派另一个操作,通常最终是一个复合操作

Of course, you can also simply dispatch another action in your callback, which usually end up being one compound action.

const myAction = ...
const callbackAction = ...

const compoundAction = () => dispatch => {
     dispatch(myAction())
         .then(() => dispatch(callbackAction()));
};

这篇关于向Redux Reducer添加回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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