在Redux Connect回调中访问状态和调度

时间:2019-06-25 22:49:31

标签: javascript reactjs redux react-redux

我有一个绑定状态和分派到一个函数的函数。例如:

function bindStateToGetFoo = (state, dispatch) => (arg1, arg2) => {
  const { val1, val1 } = state;
  dispatch(createAction());
  ...
};

之所以这样做,是因为我不想在mapStateToPropsmapDispatchToProps中重复代码。该功能用于多个组件中。做起来比较干净:

connect(
  state => ({
    someFunction: bindStateToSomeFunction(state),
  }),
  dispatch => ({
    anotherFunction: bindDispatchToAnotherFunction(dispatch),
  }),
);

但是,当一个函数既需要状态又需要调度时,我不知道如何处理它。是否可以在Redux connect回调中访问状态和调度?

1 个答案:

答案 0 :(得分:0)

您能做这样的事情吗?

function createDispatcherAndSelectorFunctions(...args) {
    return {
         dispatcher: (id, name) => ({
            type: "MY ACTION"
            payload: {
                id, name
            }
         }),              
         selector: (state) => state.foo
    } 
}


const {dispatcher, selector} = createDispatcherAndSelectorFunctions("hello world"); 

connect(
    state => ({
        data: selector(state), 
    }), 
    dispatch => ({
        fn: (id, name) => dispatch(dispatcher(id, name))
    })
);