Read Store's Initial State in Redux Reducer

前端 未结 4 1956
慢半拍i
慢半拍i 2020-11-29 15:30

Initial state in a Redux app can be set in two ways:

  • pass it as the second argument to createStore (docs link)
  • pass it as the first argum
4条回答
  •  春和景丽
    2020-11-29 15:53

    I hope this answers your request (which I understood as initializing reducers while passing intialState and returning that state)

    This is how we do it (warning: copied from Typescript code).

    The gist of it is the if(!state) test in the mainReducer(factory) function

    function getInitialState(): MainState {
    
         return {
             prop1:                 'value1',
             prop1:                 'value2',
             ...        
         }
    }
    
    
    
    const reducer = combineReducers(
        {
            main:     mainReducer( getInitialState() ),
            ...
        }
    )
    
    
    
    const mainReducer = ( initialState: MainState ): Reducer => {
    
        return ( state: MainState, action: Action ): MainState => {
    
            if ( !state ) {
                return initialState
            }
    
            console.log( 'Main reducer action: ', action ) 
    
            switch ( action.type ) {
                ....
            }
        }
    }
    

提交回复
热议问题