Load data before createStore

后端 未结 1 365
刺人心
刺人心 2021-01-24 15:58

I’ve created some React files where one initializes a Redux store. However, I really need to load some data from a json file before store is initialized.

I’ve tried to

1条回答
  •  情歌与酒
    2021-01-24 16:42

    Action types actiontypes.js

    export const LOAD_DATA_REQUEST='LOAD_DATA_REQUEST';
    export const LOAD_DATA_SUCCESS='LOAD_DATA_SUCCESS';
    export const LOAD_DATA_ERROR='LOAD_DATA_ERROR';
    

    Actions

    actions.js

    import * as Actions from './actiontypes';
    
    function load() {
        return { type: Actions.LOAD_DATA_REQUEST };
    }
    
    function success(res) {
        return { type: Actions.LOAD_DATA_SUCCESS, payload: res };
    }
    
    function error(ex) {
        return { type: Actions.LOAD_DATA_ERROR, payload: ex };
    }
    export function loadData(url) {
        return (dispatch) => {
            dispatch(load());
            axios.get(url).then((res) => {
                dispatch(success(res));
            }).catch((ex) => {
                dispatch(error(ex));
            });
        };
    }
    

    use this in reducers that requires

    import * as Actions from './actiontypes';
    const newState = Object.assign({}, state);
    switch (action.type) {
        case Actions.LOAD_DATA_REQUEST:
            {
                //maybe you load
                newState.loading = true;
                return newState;
            }
        case Actions.LOAD_DATA_SUCCESS:
            {
                const res = action.payload;
                //do what you need  for this reducer
    
                return newState;
            }
        case Actions.LOAD_DATA_ERROR:{
             /// maybe you will want to show some error message in some reducer? 
            return newState; 
        }
    }
    

    You just need the first screen of your application on componentWillMount() call the loadData() action

    I hope this can help you

    0 讨论(0)
提交回复
热议问题