在React中使用immutability-helper来设置(可能是嵌套的)对象的值

时间:2017-08-03 22:26:07

标签: javascript json reactjs nested immutability

我有这些代码:

var update=require('immutability-helper');

var state = {
  step: 1,
  fields: {
    type: '',
    name: '',
    subtype: '',
    team: '',
    agreement: ''
  }
};

function assignAttribute(attr, value) {
  var temp = update(state, {
    [attr]: {$set: value}
  });

  state = temp;
};

console.log(state); // -> { step: 1, fields: { type: '', name: '', subtype: '', team: '', agreement: '' } }
assignAttribute('step', 3);
console.log(state); // -> { step: 3, fields: { type: '', name: '', subtype: '', team: '', agreement: '' } }
assignAttribute('fields.type','superType');
console.log(state); // -> { step: 3, fields: { type: '', name: '', subtype: '', team: '', agreement: '' }, 'fields.type': 'superType' }

我想要的是最后一行如下:

{ step: '3', fields: { type: 'superType', name: '', subtype: '', team: '', agreement: '' } }

主要问题似乎是在assignAttribute函数中[attr]不再用作点符号 我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

I found a workaround (but not the right solution)

Using lodash/fp:

var _=require('lodash/fp');

var state = {
  step: 1,
  fields: {
    type: '',
    name: '',
    subtype: '',
    team: '',
    agreement: ''
  }
};

function assignAttribute(attr, value) {
  var temp = _.set(attr, value, state);

  state = temp;
};

Due to the fact that _.set is immutable I now got what I looked for :-)