ImmutableJS - 更新列表中的值

use*_*212 10 javascript reactjs immutable.js

我有这样的地图(在ImmutableJS中):

{arrayOfValues: [
  {one: {inside: 'first in array'}},
  {one: {inside: 'second in array'}}
]}
Run Code Online (Sandbox Code Playgroud)

我想更新"arrayOfValues"数组中第二个条目中的"inside"值.我该怎么做?这就是我现在所说的"Uncaught Error:invalid keyPath"

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

我也直接尝试了这个并没有用:

theMap.setIn(['arrayOfValues',1,'one','inside'],'updated value');
Run Code Online (Sandbox Code Playgroud)

经过几个小时的寻找解决方案,我感谢任何帮助.谢谢.

Bri*_*ark 14

你在做什么是正确的(参见这个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' } },
//   ]
// }
Run Code Online (Sandbox Code Playgroud)

当你打电话时orig.setIn(),它不会orig直接修改.这就是这个Immutable库的全部目的.它不会改变现有数据,而是从现有数据中创建一个新数据.


Bri*_*ent 2

您的setIn示例的工作原理如下: http://plnkr.co/edit/1uXTWtKlykeuU6vB3xVO ?p=preview

也许您假设 的值theMap会因 ? 的结果而改变setIn

由于这些结构是不可变的,因此您必须在新变量中捕获修改后的值,如下所示var theMap2 = theMap.setIn(['arrayOfValues',1,'one','inside'],'updated value');