[英]Object spread , new Redux state
我在 redux 中有以下 state object:
console.log({ jobOffers: { filters: { employments: [], careerLevels: [], jobTypeProfiles: [], cities: [], countries: [], searchTerm: '', currentPage: 1, pageSize: 5 } } });
我想将数组就业设置为新的。
那是我的 redux 减速机:
export const reducer = (state = initialStateData, action) => { switch (action.type) { case Action.SET_ARR_FILTER: { const newNestedState = {...state[action.key], [action.key]: action.value, }; return {...state, [action.key]: newNestedState }; } default: return state; } };
那个行动:
export const SET_ARR_FILTER = 'SET_ARR_FILTER'; export const setEmployment = employment => ({ type: SET_ARR_FILTER, key: 'employments', value: employment, });
但是我的 object 在减速器被调用后看起来像这样:
console.log({ employments: { employments: ['HelloWorld'] }, })
这里有什么问题?
你的层次太深(或不够深,取决于你如何看待它)。
你需要类似的东西:
case Action.SET_ARR_FILTER:
{
const { filters } = state
return { ...state,
filters: {
...filters,
[action.key]: action.value
}
};
}
与马克的回答类似,如果您愿意,可以全部一行。
export const reducer = (state = initialStateData, action) => {
switch (action.type) {
case Action.SET_ARR_FILTER:
return {
...state,
filter: {
...state.filter,
[action.key]: action.value
}
}
default:
return state;
}
};
终于自己搞定了。 答案是:
case Action.SET_ARR_FILTER: { return {...state, jobOffers: {...state.jobOffers, filters: {...state.jobOffers.filters, [action.key]: action.value }, }, }; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.