Если вы создаете более общее действие, которое отправляет родительский элемент как часть действия
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;
}
};
DEMO
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);