简体   繁体   English

Object 传播,新 Redux state

[英]Object spread , new Redux state

I have the following state object in redux:我在 redux 中有以下 state object:

 console.log({ jobOffers: { filters: { employments: [], careerLevels: [], jobTypeProfiles: [], cities: [], countries: [], searchTerm: '', currentPage: 1, pageSize: 5 } } });

I want to set the array employments new.我想将数组就业设置为新的。

That's my redux reducer:那是我的 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; } };

The action:那个行动:

 export const SET_ARR_FILTER = 'SET_ARR_FILTER'; export const setEmployment = employment => ({ type: SET_ARR_FILTER, key: 'employments', value: employment, });

But my object looks like this after the reducer has been called:但是我的 object 在减速器被调用后看起来像这样:

 console.log({ employments: { employments: ['HelloWorld'] }, })

What is wrong here?这里有什么问题?

You're a level too deep (or not deep enough, depending on how you see it).你的层次太深(或不够深,取决于你如何看待它)。

You need something like:你需要类似的东西:


case Action.SET_ARR_FILTER:
      {
        const { filters } = state
        return { ...state,
          filters: {
            ...filters,
            [action.key]: action.value 
          }
        };
      }

Similar to Mark's answer, all one line if you like.与马克的回答类似,如果您愿意,可以全部一行。

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;
  }
};

Finally got it myself.终于自己搞定了。 Answer is:答案是:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM