我有一个绑定状态和分派到一个函数的函数。例如:
function bindStateToGetFoo = (state, dispatch) => (arg1, arg2) => {
const { val1, val1 } = state;
dispatch(createAction());
...
};
之所以这样做,是因为我不想在mapStateToProps
和mapDispatchToProps
中重复代码。该功能用于多个组件中。做起来比较干净:
connect(
state => ({
someFunction: bindStateToSomeFunction(state),
}),
dispatch => ({
anotherFunction: bindDispatchToAnotherFunction(dispatch),
}),
);
但是,当一个函数既需要状态又需要调度时,我不知道如何处理它。是否可以在Redux connect
回调中访问状态和调度?
答案 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))
})
);