问题
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 singlekeyPath
argument, which in your case is[ 'members' ]
. The second argument (removing
) is ignored, so the result is that the entiremembers
map is deleted; instead,removing
should become part of the key path.removing
is aNumber
, but because you're creating aMap
from a JS object, its keys will beString
'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