【问题标题】:Object spread , new Redux state对象传播,新的 Redux 状态
【发布时间】:2020-02-08 07:28:59
【问题描述】:

我在 redux 中有以下状态对象:

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

我想将数组就业设置为新的。

那是我的 redux reducer:

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

但是在调用 reducer 后我的对象看起来像这样:

console.log({

  employments: {
    employments: ['HelloWorld']
  },

})

这里有什么问题?

【问题讨论】:

  • 如果您要使用 A 和 B 发送 setEmployment 两次,您希望结果仅包含 B(即 employments: ['B'])还是同时包含 A 和 B(employments: ['A', 'B'])?
  • 它应该包含两个值

标签: javascript redux spread-syntax


【解决方案1】:

你的关卡太深(或不够深,取决于你如何看待它)。

你需要这样的东西:


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

【讨论】:

  • 如果你的 state 中不仅仅是 filters,你可能需要考虑将它分解成多个 reducer。了解之前和之后的就业情况以及在这种情况下的就业情况也很有用。无论哪种方式,概念都是一样的:返回扩展状态、覆盖目标键、扩展子状态、覆盖目标键等。
【解决方案2】:

与 Mark 的回答类似,如果你愿意,可以全部一行。

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

【讨论】:

  • 给出语法错误。那 state.filters 不能以这种方式工作
  • @Gutelaunetyp 已更新,很难正确回答,因为您没有定义接口和类型,但我认为应该这样做
【解决方案3】:

终于自己搞定了。答案是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2020-09-30
    • 2018-03-20
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多