0

我的反应应用程序中有这个组件,它依赖于来自 api 服务器的一些数据。我使用了反应Suspense,但这只是延迟加载我的组件然后显示,即使数据尚未从 API 服务器到达。

然后我如何等到数据到达之前显示依赖于该数据的 UI,并且在组件等待时,应用程序应该让用户忙于加载程序。

4

1 回答 1

0

解决方案

从我上面的问题来看,这很容易在没有任何第三方库的情况下实现。你只需要创建一个简单的 react 类组件,它需要三个带有函数类型的 props。


import { Component } from "react";
import PropTypes from "prop-types";

/**
 * SuspendUI and fetch resources from api server.
 *
 * @template SuspendUI
 */
class SuspendUI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      /** by default render loader while resources are been fetched. */
      suspendui: true,
      /** if api server request fails render error fallbak  */
      hasError: false,
    };
  }

  componentDidMount() {
    var fetch = this.props.fetch,
      isFunc;

    isFunc = typeof fetch === "function";
    if (isFunc) {
      fetch()
        .then((result) => {
          // display ui components when promise is resolved
          this.setState({ suspendui: false, hasError: false });
        })
        .catch((err) => {
          this.setState({ suspendui: false, hasError: true });
        });
    } else {
      throw new Error("Fetch prop must be a function.");
    }
  }

  render() {
    /* 
      When the component is initally mounted it display 
      the loader while fetch resources from api server.
      But as soon as the resources are fetch and the server return 
      good response the ctrl is passed to the third if statement.
    */
    if (this.state.suspendui) {
      return this.props.loader();
    }

    /* 
      When the hasError occourd it means that the api server 
      return or the request lib return a promise that was rejected.
      The error fallback component is render to the user.
    */
    if (this.state.hasError) {
      return this.props.errorfallback();
    }

    /**
     * At this point return the children of the UISuspense
     * since all the is good.
     * ____
     * The api server return the data as expected and the
     * resources data has been consumed by state or context update
     */
    if (!this.state.hasError && !this.state.suspendui) {
      return this.props.children;
    }
  }
}

/* Validation for allowed props types  */
SuspendUI.propTypes = {
  /** @type {Function} */
  loader: PropTypes.func,
  /** @type {Function}  */
  errorfallback: PropTypes.func,
  /**
   * @type {Function}
   */
  fetch: PropTypes.func,
};

export { SuspendUI };

这就是你所需要的!

您可以通过 npm 检查使用我已经编译用于生产的那个

npm i suspendui

于 2021-06-19T15:43:40.247 回答