简体   繁体   English

ImmutableJS - 更新列表中的值

[英]ImmutableJS - update value in a List

I have a Map like this (in ImmutableJS): 我有这样的地图(在ImmutableJS中):

{arrayOfValues: [
  {one: {inside: 'first in array'}},
  {one: {inside: 'second in array'}}
]}

And I want to update the value "inside" in the second entry in the "arrayOfValues" array. 我想更新“arrayOfValues”数组中第二个条目中的“inside”值。 How can I do it? 我该怎么做? This is what I have now and it says "Uncaught Error: invalid keyPath" 这就是我现在所说的“Uncaught Error:invalid keyPath”

theMap.update('arrayOfValues',(list)=>{
  return list.setIn([1,'one','inside'],'updated value'); 
})

I also tried directly this and it didn't work: 我也直接尝试了这个并没有用:

theMap.setIn(['arrayOfValues',1,'one','inside'],'updated value');

After several hours of looking for the solution, I appreciate any help. 经过几个小时的寻找解决方案,我感谢任何帮助。 Thank you. 谢谢。

What you are doing is correct (see this JSBin ). 你在做什么是正确的(参见这个JSBin )。

const orig = Immutable.fromJS({
  arrayOfValues: [
    { one: { inside: 'first in array' } },
    { one: { inside: 'second in array' } },
  ]
});

const updated = orig.setIn(['arrayOfValues', 1, 'one', 'inside'], 'updated value');

console.log(updated.toJS());

// {
//   arrayOfValues: [
//     { one: { inside: 'first in array' } },
//     { one: { inside: 'second in array' } },
//   ]
// }

When you call orig.setIn() , it doesn't modify orig directly. 当您调用orig.setIn() ,它不会直接修改orig That's the whole purpose of this Immutable library. 这就是这个Immutable库的全部目的。 It doesn't mutate the existing data but creates a new one from the existing one. 它不会改变现有数据,而是从现有数据中创建一个新数据。

Your setIn example works as you should see in this plunkr: http://plnkr.co/edit/1uXTWtKlykeuU6vB3xVO?p=preview 您的setIn示例的工作原理与您在此plunkr中看到的一样: http ://plnkr.co/edit/1uXTWtKlykeuU6vB3xVO?p = preview

Perhaps you are assuming the value of theMap will be changed as a result of the setIn ? 也许你正在承担的价值theMap将被改变为的结果setIn

As these structures are immutable, you must capture the modified value in a new variable as var theMap2 = theMap.setIn(['arrayOfValues',1,'one','inside'],'updated value'); 由于这些结构是不可变的,因此必须在新变量中捕获修改后的值,如var theMap2 = theMap.setIn(['arrayOfValues',1,'one','inside'],'updated value');

activePane is the index of Object in Array(List) that I had to modify activePane是我必须修改的Array(List)中Object的索引

case CHANGE_SERVICE:
  var obj = {
    title: '1212121 Tab',
    service: '',
    tagName: '',
    preDefinedApi: '',
    methodType: '',
    url: '',
    urlParams: [{
      label: '',
      name: '',
      value: '',
    }],
    headers: [{
      label: '',
      name: '',
      value: '',
    }],
  };
  var activePane = state.get('activePane');
  var panes = state.setIn(['panes', activePane, 'service'], action.val);

  return state.setIn(['panes', activePane, 'service'], action.val);

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

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