在Redux reducer中更新嵌套对象

时间:2017-12-20 18:47:22

标签: javascript reactjs react-native ecmascript-6 redux

我有以下减速器:

import {
  // QuestionForm
  UPDATE_QUESTION_FORM,
  // FoodPreferenceList
  UPDATE_FOOD_PREFERENCE,
  UPDATE_NUMBER_OF_MEALS
} from '../actions/types';

const INITIAL_STATE = {
  setupComplete: false,
  error: '',
  loading: false,
  // QuestionForm
  questionForm: {
    gender: 'Female',
    age: '35',
    weight: '75',
    height: '175',
    activityLevel: '1.2',
    goal: '100',
    maintenanceCalories: '',
    goalCalories: '',
  },
  // FoodPreferenceList
  selectedFoodsArrays: [],
  numberOfMeals: '1'
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    // QuestionForm
    case UPDATE_QUESTION_FORM:
      return { ...state, questionForm.[action.payload.prop]: action.payload.value };
    // FoodPreferenceList
    case UPDATE_FOOD_PREFERENCE:
      return { ...state, selectedFoodsArrays: action.payload };
    case UPDATE_NUMBER_OF_MEALS:
      return { ...state, numberOfMeals: action.payload };
    // DEFAULT
    default:
      return state;
  }
};

我在引用我状态中存储的一个对象时遇到了一些麻烦。问题在于:

case UPDATE_QUESTION_FORM:
  return { ...state, questionForm.[action.payload.prop]: action.payload.value };

我得到以下ESLint Error。我正在尝试使用值更新questionForm条目的元素。 questionForm中更新的元素由参数决定。格式似乎不正确,谷歌搜索没有帮助。

示例

questionForm.[gender]: 'Male'
  • 这会更新gender的{​​{1}}密钥,其值为questionForm

1 个答案:

答案 0 :(得分:5)

你要做的是添加另一层嵌套:

case UPDATE_QUESTION_FORM:
  return { 
    ...state, 
    questionForm: {
      ...state.questionForm,
      [action.payload.prop]: action.payload.value 
    }
  };

这使用扩展语法和计算属性名称(来自ES6)将表达式用作对象键。