在 createStore 之前加载数据

Load data before createStore

我创建了一些 React 文件,其中一个初始化 Redux 存储。但是,我确实需要在初始化存储之前从 json 文件加载一些数据。

我尝试导入脚本加载 json 结构,然后将其分配给 createStore initialState 值。但是 createStore 在加载和分配数据之前运行。

有什么简单的方法可以说“在我的 axios 调用完成之前不要做任何事情”吗???

动作类型 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.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));
        });
    };
}

在需要

的减速器中使用它
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; 
    }
}

您只需要在应用程序的第一个屏幕上调用 componentWillMount() 的 loadData() 操作

希望对您有所帮助