【问题标题】:How to make a single loader reducer for whole application, React如何为整个应用程序制作单个加载器减速器,React
【发布时间】:2018-11-05 17:57:09
【问题描述】:

我有一个应用程序,其中有多个组件以及每个组件的操作和减速器。我也在使用 redux-pack 进行承诺处理。

所以情况就是这样,我只想为我的整个应用程序使用一个减速器来处理我的页面加载器。这意味着,每当 API 调用开始时,加载程序应该显示,并且在 API 结束时应该隐藏。我不想为此编写单独的操作。

请帮助我提出您的建议。提前致谢。

【问题讨论】:

  • 您找到最佳方法了吗?我也在找这个
  • 是的,我做到了。这是一种直接的方法
  • @Abinthaha:你能分享一下你找到的解决方案吗?
  • 嗨@VimalPatel,解决方案是直接的。我有一个加载器减速器,我在 API 调用开始时调度 show 事件,在 API 完成时调度 stop 事件。加载器在根级别被调用,其状态将根据来自减速器的值而改变。如果您还有其他疑问,请告诉我
  • @Abinthaha 感谢您提供的信息,如何识别调度操作是否是 API 调用,我想我们需要实现一个自定义中间件来做到这一点。您有一些与此相关的示例代码吗?我正在寻找通用解决方案

标签: reactjs redux react-redux redux-promise-middleware


【解决方案1】:

,我没有正确的想法redux-pack,但我已经使用react-redux 实现了这一点。有库react-loading-overlay 库你可以使用它或创建一个新的loading-overlay 自己的。

https://github.com/derrickpelletier/react-loading-overlay图书馆的链接,如果你想要的话。

现在来看代码:-

我在 redux 中创建了一个名为 loadingState 的全局状态

//this is my action.
export const ENABLE_OR_DISABLE_LOADING = 'ENABLE_OR_DISABLE_LOADING';

export function enableOrDisableLoading (value = true, msg='Loading your content') {
    return {
        type: ENABLE_OR_DISABLE_LOADING,
        payload: {isLoading: value, msg: msg}
    };
}

//this is my reducer.
export function loading(state={isLoading: false, msg: 'Please wait...'}, action) {
    switch (action.type) {
        case ENABLE_OR_DISABLE_LOADING:
            return action.payload;
        default:
            return state;
    }
}

Add this reducer to your store.


My HOC is like this.

import LoadingOverlayWrapper from 'react-loading-overlay';


class AdminImpl extends React.Component {
  return (
            <LoadingOverlayWrapper
                active={this.props.isLoading}
                spinner
                zIndex={1000}
                className="height100"
                text={this.props.msg}
            >
             <SideBar/>
             {this.props.child}
            </LoadingOverlayWrapper>
        );
}

const mapStateToProps = (state) => {
    return state.loading;
};

export const Admin = connect(mapStateToProps)(AdminImpl);



Now dispatch action from anywhere from your app.

//start Loading state
store.dispatch(enableOrDisableLoading(true, 'Your loading msg'));

//start Loading state
store.dispatch(enableOrDisableLoading(false));

【讨论】:

  • 谢谢,但我正在寻找更优化的方法。
猜你喜欢
  • 2020-02-19
  • 2012-01-22
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多