简体   繁体   English

更新Redux Reducer中的嵌套对象

[英]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 . 我收到以下ESLint错误 I am trying to update an element of the questionForm entry with a value. 我试图用一个值更新questionForm表单项的元素。 The element updated in questionForm is decided by an argument. questionForm更新的元素由参数决定。 The format seems to be incorrect and Google Search has not helped out. 格式似乎不正确,并且Google搜索没有帮助。

Example

questionForm.[gender]: 'Male'
  • This will update the gender key of questionForm with the value 'Male' . 这将使用值'Male'更新questionFormgender关键字。

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. 这将使用扩展语法以及计算所得的属性名称(来自ES6)来将表达式用作对象键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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