【问题标题】:How to handle a single loading indicator for the whole application using React and Redux?如何使用 React 和 Redux 处理整个应用程序的单个加载指示器?
【发布时间】:2020-02-19 14:31:51
【问题描述】:

我的 Web 应用程序有时需要轮询后端以获取数据。这些操作通常需要大约 6 或 7 秒。在这些投票期间,我希望不允许用户在 UI 上进行交互。

我所做的是,在每个组件状态下,都有一些标志,例如loadingsuccesserror,用于显示组件级别的加载状态。但是用户仍然可以与其他组件交互 => 这使得处理边缘情况非常困难。因此,我希望当应用程序处于轮询状态时,用户不能在其他组件上进行交互以获得可预测且一致的流程。

我期望的是,只要有轮询,就会出现一个模态弹出窗口,然后用户只能看到具有某些加载状态的模态弹出窗口,并且无法在 UI 上进行交互。

你们能给我建议一个方向吗?使用 Redux(如果我可以重用来自 Antd https://ant.design/components/modal/#header 的模态弹出窗口会更好)。

【问题讨论】:

  • 使用什么 UI 库并不重要。您可以在您的父组件(包含 Switch-Router(如果有的话)的组件)中打开您的模式,并从顶层阻止所有其他组件。
  • 您在寻找什么样的答案?您只需要调度一个动作并在需要时显示模态覆盖

标签: reactjs redux antd


【解决方案1】:

让我分享我的代码

route_reducer.js

const INITIAL_STATE = {
  ....
  errorMessage: "",
  loading: false
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    ....
    case UPDATE_ERROR:
      return {
        ...state,
        errorMessage: action.payload.error,
        loading: action.payload.loading
      };

    default:
      return state;
  }
};


route_actions.js

//update loading spinner and error message
export const updateErrorAndLoading = (error = "",loading = false) => async dispatch => {
  dispatch({ type: UPDATE_ERROR, payload: { error, loading } });
};

Home.js

你应该处理一些条件渲染(在你的应用程序中)。如果this.props.loading 为真,则显示微调器,不显示其他组件...等等。

import {  Spin } from "antd";

class Home extends Component {

render() {
//you can pass error message or check some conditions like 
//this.props.errorMessage.trim() === "" ?null: <div>your custom componet..etc, {this.props.errorMessage}</div>

 const spinner = this.props.loading ? (
      <Spin size="large" className="spinner" />
    ) : null;

 return (
   <>
    {/* spinner */}
    {spinner}
   </>


const mapStateToProps = state => {
  return {
     ...,
    errorMessage: state.route.errorMessage,
    loading: state.route.loading
  };
};

export default connect(
  mapStateToProps,
  actions
)(Home);

App.css 根据您的需要制作.spinner 位置fixedabsolute 并提供您自己的CSS 属性

/* spinner */
.spinner {
    position: fixed !important;
    top: 10em;
    margin-left: 10px !important;
    margin-top: 10px !important;
    height: 50px;
    left: 1em;
    z-index: 200;
}

在您的任何组件中,您都可以传递错误消息或加载状态

showSpinner=()=>{
this.props.updateErrorAndLoading("some error occured", true);
}
closeSpinner=()=>{
this.props.updateErrorAndLoading(undefined, undefined);
}

整页

让我知道你是否能够实现这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 2018-11-05
    • 2017-08-17
    • 2020-11-05
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多