我正在使用pepperoni-app-kit作为Immutable.js附带的react-native。我之前从未使用过Immutable.js,我发现很难执行一个简单的任务
我想在消息列表中推送消息,该消息位于Map中。
someReducer.js
import {Map,List} from 'immutable';
const initialState = Map({isReady : false , messages : List([])});
// reducer switch case
return state.update('messages',messages=>messages.concat(action.Message.payloadString);
// not working
//I also tried
return state.get('messages').push(Immutable.Map({text:'some text',...}))
如何使用Immutable.js
编写此ES6代码var newState = state; // copy state
newState.messages.push({text:'hello world',...otherInfo}); // make changes
return object.assign({},newState); // return a new object.
答案 0 :(得分:2)
describe('how-to-perform-push-operation-in-a-nested-immutable-js-map-and-lists', () => {
const initialState = Immutable.Map({
isReady: false,
messages: Immutable.List([]),
});
it('should `push` using List.update', () => {
const payload = 'some text';
const updatedState = initialState.update('messages',
(list) => (list.push(payload))
);
// passes:
expect(updatedState.getIn(['messages', 0])).to.equal(payload);
});
it('should `concat` using List.update', () => {
const multiMessagePayload = ['alpha', 'beta'];
const reUpdatedState = initialState.update('messages',
(list) => (list.concat(multiMessagePayload))
);
// passes:
expect(reUpdatedState.get('messages').size).to.equal(2);
});
});