如何将这两个冗余操作合并为一个



我有两个表单字段a和b。我需要为这两种情况调度一个通用操作,但应该相应地更新存储。

switch (action.type) {
case actions.ONINIT_a:
return {
...state,
parent: {
...state.parent,
a: {
...state.parent.a,
...action.data
}
}
};
case actions.ONINIT_b:
return {
...state,
parent: {
...state.parent,
b: {
...state.parent.b,
...action.data
}
}
};
default:
return state;
}
};

如果您创建了一个更通用的操作,将父操作作为操作的一部分发送

const initParent = (data, parent) => ({
type: ON_INIT,
data,
parent
});

然后你可以推广减少

switch (action.type) {
case actions.ON_INIT:
return {
...state,
parent: {
...state.parent,
[action.parent]: {
...state.parent[action.parent],
...action.data,
}
}
};
default:
return state;
}
};

演示

const actions = {
ON_INIT: 'ON_INIT',
};
const initParent = (data, parent) => ({
type: actions.ON_INIT,
data,
parent
});
const initialState = {
parent: {},
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actions.ON_INIT:
return {
...state,
parent: {
...state.parent,
[action.parent]: {
...state.parent[action.parent],
...action.data,
}
}
};
default:
return state;
}
};
let nextState;
nextState = reducer(initialState, initParent({ test: "data - a" }, "a"));
console.log("Update 1:", nextState);
nextState = reducer(nextState, initParent({ test: "data - b" }, "b"));
console.log("Update 2:", nextState);
nextState = reducer(nextState, initParent({ test: "new data - a" }, "a"));
console.log("Update 3:", nextState);

您可以使用react批处理中间件,一次调度多个操作,如下所示:

dispatch([{ type: actions.ONINIT_a }, { type: actions.ONINIT_b }])

或者编写自己的redux中间件来实现同样的目的。

相关内容

  • 没有找到相关文章

最新更新