简体   繁体   中英

Update nested object in Redux reducer

I have the following reducer:

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

I am having a bit of trouble referencing one of the objects stored in my state. The problem is with the line:

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

I get the following ESLint Error . I am trying to update an element of the questionForm entry with a value. The element updated in questionForm is decided by an argument. The format seems to be incorrect and Google Search has not helped out.

Example

questionForm.[gender]: 'Male'
  • This will update the gender key of questionForm with the value 'Male' .

What you would do is add another level of nesting:

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

This uses spread syntax along with computed property names (from ES6) to use an expression as an object key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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