Load data before createStore

↘锁芯ラ 提交于 2020-01-11 12:08:30

问题


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 import a script loading the json structure then assigning it to the createStore initialState value. But createStore runs before the data is loaded and assigned.

Is there any simple way to say “dont do anything before my axios call is done”???


回答1:


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



来源:https://stackoverflow.com/questions/47160976/load-data-before-createstore

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