最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does Immutable.js throw Invalid key path on Map.setIn() - Stack Overflow

programmeradmin1浏览0评论

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());

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());
Share Improve this question edited Jun 8, 2016 at 22:25 Seth 10.5k10 gold badges48 silver badges69 bronze badges asked Jun 8, 2016 at 21:02 hally9khally9k 2,5832 gold badges29 silver badges51 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 38

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>

发布评论

评论列表(0)

  1. 暂无评论