更新reducer中对象的状态

时间:2018-10-30 05:22:41

标签: javascript reactjs redux react-redux

enter image description here我是新来响应js的人。在这里,我确实具有可以添加或删除三个差异行的功能。我有一个减速器,

const initialState = {
    Low: [
        {
            id: 'L0',
            technologyId: 0,
            technology: '',
            type: '',
            count: '',
            level: 'EASY'
        }
    ],
    Medium: [
        {
            id: 'M0',
            technologyId: 0,
            technology: '',
            type: '',
            count: '',
            level: 'Medium'
        }
    ],
    High: [
        {
            id: 'H0',
            technologyId: 0,
            technology: '',
            type: '',
            count: '',
            level: 'Tough'
        }
    ],

所以,在这里,我想将其作为通用名称,所以,我试图单击加号添加对象,然后在-上删除。所以,

在这里,我要添加使用,

const tempObj = {
      id: tempvar + id,
      technologyId: 0,
      technology: temp[0].technology,
      type: type,
      count: '',
      level: addtype
    }

我现在创建此对象取决于我将其添加到该特定数组中的addType。

我是用这种方式做的

const addData = [...this.props.lowData[addtype], tempObj];

    this.props.addNewTech(addData);

因此,这里的...this.props.lowData[addtype]返回的对象不是数组,这是问题吗?如果是,它将返回一个数组而不是对象,但是它如何返回对象而不是数组。 我的props.lowData就像,

一个具有三个不同数组的对象,我的意思是与reducer相同。但是,每次添加它时,该元素仅在Low数组中添加,而不在中层或高层。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

问题出在reducer中,您仅更新Low属性。您需要检查哪些属性需要更新。为此,您可以像这样将addtype传递给动作创建者

this.props.addNewTech({ addData, addtype });

然后是动作创建者

export function addNewTech(data) { 
  return {
     type: ADD_NEW, 
     data //is equavalent to data: data (ES6)
  } 
} 

然后在reducer中动态更新对象

    case ADD_NEW: 
      return { 
        ...state, 
        //here choose the property to be updated dynamically
        //replace Low: action.data with below line
        [action.data.addtype]: action.data.addData, 
        error: false, 
      } 

**请注意[action.data.addtype]: action.data.addData,我们在ES6中使用计算的属性名称。

相关问题