在createStore之前加载数据 [英] Load data before createStore

查看:76
本文介绍了在createStore之前加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

有没有一种简单的方式说在完成axios呼叫之前不要做任何事情"?

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

推荐答案

操作类型 actiontypes.js

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.js

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()操作

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

我希望这可以为您提供帮助

I hope this can help you

这篇关于在createStore之前加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆