Immutable.js deleteIn not working

雨燕双飞 提交于 2019-12-23 21:21:25

问题


I have been trying to solve this problem, but there is probably something of Immutable.js that I don't catch. I hope somebody can help me to understand.

I have a test like this:

import {List, Map} from 'immutable';
import {expect} from 'chai';

import {setInitial,
        addAtListOfMembers,
        removeAtListOfMembers
        } from '../src/core';


      describe('removeAtListOfMembers', () => {

        it('remove a member to the list of members', () => {
          const state = Map({
            removing: 3,
            infos : Map(),
            members: Map({
                1:Map({
                    userName:'René',
                    date:'12/02/2016'
                }),
                2:Map({
                    userName:'Jean',
                    date:'10/03/2016'
                }),
                3:Map({
                    userName:'Elene',
                    date:'05/01/2016'
                })
              })
          });
          const nextState = removeAtListOfMembers(state);

          expect(nextState).to.equal(Map({
            infos : Map(),
            members: Map({
                1:Map({
                    userName:'René',
                    date:'12/02/2016'
                }),
                2:Map({
                    userName:'Jean',
                    date:'10/03/2016'
                })
              })
          }));
        });
      });
});

...witch tests this funtion:

export function removeAtListOfMembers(state) {
  const members = state.get('members');

  const removing = state.get('removing');

  return state
        .deleteIn(['members'], removing)
        .remove('removing');
}

but it doesn't work. I have tryed everything.... changing the line to make it work, but I don't get the item number 3 deleted.

What's wrong? Somebody to help me?


回答1:


This should work:

export function removeAtListOfMembers(state) {
  const members = state.get('members');

  const removing = state.get('removing');

  return state
        .deleteIn(['members', String(removing) ])
        .remove('removing');
}

Your code has two issues:

  • deleteIn takes a single keyPath argument, which in your case is [ 'members' ]. The second argument (removing) is ignored, so the result is that the entire members map is deleted; instead, removing should become part of the key path.
  • removing is a Number, but because you're creating a Map from a JS object, its keys will be String's (this is mentioned in the documentation as well):

    Keep in mind, when using JS objects to construct Immutable Maps, that JavaScript Object properties are always strings

So you need to convert removing to a String when passing it to deleteIn.



来源:https://stackoverflow.com/questions/37628154/immutable-js-deletein-not-working

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