How to use Immutable.js with redux?

后端 未结 5 839
-上瘾入骨i
-上瘾入骨i 2020-12-07 09:53

Redux framework is using reducers to change app state in response to an action.

The key requirement is that a reducer cannot modify an existing state object; it must

5条回答
  •  遥遥无期
    2020-12-07 10:11

    The accepted answer should not be the accepted answer. You need to initialise state using immutable and then (as mentioned before) use redux-immutablejs

    const initialState = Immutable.fromJS({}) // or Immutable.Map({})
    
    const store = _createStore(reducers, initialState, compose(
        applyMiddleware(...middleware),
        window.devToolsExtension ? window.devToolsExtension() : f => f
    ));
    

    Than use the combineReducers from redux-immutablejs

    Extra tip: Using react-router-redux works pretty well so if you would like to add this then replace the reducer from react-router-redux with this:

    import Immutable from 'immutable';
    import {
        UPDATE_LOCATION
    } from 'react-router-redux';
    
    let initialState;
    
    initialState = Immutable.fromJS({
        location: undefined
    });
    
    export default (state = initialState, action) => {
        if (action.type === UPDATE_LOCATION) {
            return state.merge({
                location: action.payload
            });
        }
    
        return state;
    };
    

    Just import this into your root reducer

    This is also stated in the documentation of redux-immutablejs

提交回复
热议问题