Immutable.js 推入嵌套对象中的数组

Immutable.js Push into array in nested object

假设有一个对象:

const object = {
  'foo': {
    'bar': [1, 2, 3]
  }
}

我需要将 4 推入 object.foo.bar 数组。

现在我是这样做的:

const initialState = Immutable.fromJS(object)
const newState = initialState.setIn(
  ['foo', 'bar', object.foo.bar.length],
  4
)
console.log(newState.toJS())

但我不太喜欢它,因为我需要在路径中使用 object.foo.bar.length。在我的真实示例中,对象嵌套得更深,获取数组的长度看起来非常难看。还有其他更方便的方法吗?

这应该有效

initialState.updateIn(['foo', 'bar'], arr => arr.push(4))

参考文献:

我正在使用 seamless-immutable,当我将新项目添加到嵌套对象数组时,出现此错误:

The push method cannot be invoked on an Immutable data structure.

我的数组还有 push 方法,但它不起作用。解决方案是改用 concat,有关 #43:

的更多详细信息
initialState.updateIn(['foo', 'bar'], arr => arr.concat([4]));

希望对您有所帮助!