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

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

问题描述

我创建了一些 React 文件,其中一个用于初始化 Redux 存储.但是,我确实需要在 store 初始化之前从 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

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

希望对你有帮助

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

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