javascript - 我可以使用 setIn 在空数组上创建新索引吗?

标签 javascript reactjs

我的问题是,在此结构中使用不可变:

myMap = Map({a: [], b: []});
myMAp.setIn(['a', 0], 'v');

这是一个异常

immutable.js:870 Uncaught (in promise) Error: invalid keyPath
    at invariant (immutable.js:870)
    at updateInDeepMap (immutable.js:1974)
    at updateInDeepMap (immutable.js:1980)
    at Map.updateIn (immutable.js:1278)
    at Map.setIn (immutable.js:1256)

我知道我可以检查这样的索引是否存在,如果不存在则初始化,然后尝试更新,但也许功能请求是可行的,所以不可变让我们一步完成此操作。我没有看到 inmutable 在此用例上引发异常的任何动机。 我正在阅读 http://untangled.io/immutable-js-all-the-examples-youll-ever-need-to-get-set-and-delete-data-from-lists/ 上的库规范 我的建议是列表中的正常内容:

If an index doesn’t exist anywhere in the keyPath, then List.setin() will do one of the following:

If the index preceding the bad index references a List, then the bad index is trying to insert a value at a place outside of the bounds of this list. Usual rules apply, and the List expands, the value is placed at the end of the expanded List, and nulls are inserted in between. Try it for yourself in the example below, by replacing the last line with avengersList.setIn([1, 1, 1, 3], 'scarletWitch'); If the index preceding the bad index is a value (i.e. not a List or Map), then the bad index is trying to insert a value into a data type that has no concept of an index; accordingly, an Invalid keyPath error will be thrown. Try it for yourself in the example below, by replacing the last line with avengersList.setIn([0, 1], 'scarletWitch');. This tries to insert ‘scarletWitch’ into the String ‘ironMan’, and that’s never going to work!

最佳答案

你的问题并不完全有意义,因为你说你想在列表中创建一个新索引,但你试图访问一个不存在的keyPath(它是一个空数组,所以它还没有 [0] 索引),但是对象属性确实存在,它保存着这个 keyPath,所以这就是你想要的使用时,您需要 updateIn 而不是 setIn。我认为它应该是这样的:

//a doesn't have to be an `Immutable.List`, it can be a plain JS array
var myMap = Immutable.Map({a: Immutable.List([]), b: []}) 
var Rogelio = myMap.updateIn(['a'], list => list.push(0))
console.log(Rogelio)

关于javascript - 我可以使用 setIn 在空数组上创建新索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46980188/

相关文章:

css - MUI JSS 组合媒体查询而不重复

javascript - 获取 DropdownItem 的 Label 或值以将文本值设置为 DropdownToggle

javascript - 将类对象传递给 ReactJS 组件

javascript - 如何使用 webpack4 正确拆分常见依赖项

javascript - 使用 ctx.getTransformation() 获取变换后的 Canvas 鼠标坐标

Javascript:将 undefined variable 传递给函数

javascript - ReactJS 渲染带有 url 变化的 subview

c# - 如何对 <HEAD> 部分中的文件进行版本控制?

javascript - 检索字段时出错,javascript minifier 错误

reactjs - GraphQL 返回数据但在代码中未定义