Why does Immutable.js throw Invalid key path on Map.setIn()

馋奶兔 提交于 2019-12-22 01:28:41

问题


I must be missing something here because the Docs make it out as if the below code should work just fine but I get an invalid keypath error... Check this codepen.

var map1 = Immutable.Map({ 'selector': { 'type': 'bar' }});
var map2 = map1.setIn(['selector', 'type'], 'foo');
console.log(map2.toJS());

回答1:


This happens because the key 'selector' has a non-Map value. setIn will work if we make sure that the value for 'selector' is also an Immutable Map:

var map1 = Immutable.Map({ 'selector': Immutable.Map({ 'type': 'bar' })});
var map2 = map1.setIn(['selector', 'type'], 'foo');
console.log(map1.toJS());  
console.log(map2.toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>

To deeply convert JavaScript Objects and Arrays to Maps and Lists you can use fromJS(). So you can more easily write:

var map3 = Immutable.fromJS({ 'selector': { 'type': 'bar' }});
var map4 = map3.setIn(['selector', 'type'], 'foo');
console.log(map3.toJS());  
console.log(map4.toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>



回答2:


Something similar happened to me:

I was trying to access a simple selector like so:

var map1 = Immutable.Map({ 'selector': 'bar' });
var map2 = map1.setIn(['selector', 'bar'], 'foo');

This also throws the same error



来源:https://stackoverflow.com/questions/37712871/why-does-immutable-js-throw-invalid-key-path-on-map-setin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!