Load data before createStore

不打扰是莪最后的温柔 提交于 2019-12-02 05:43:05

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!