PromiseRender.js 1.42 KB
Newer Older
ddcat1115's avatar
ddcat1115 committed
1 2 3 4
import React from 'react';
import { Spin } from 'antd';

export default class PromiseRender extends React.PureComponent {
afc163's avatar
afc163 committed
5
  state = {
6
    component: null,
afc163's avatar
afc163 committed
7
  };
8
  componentDidMount() {
9 10 11 12 13 14 15 16 17 18 19
    this.setRenderComponent(this.props);
  }
  componentWillReceiveProps(nextProps) {
    // new Props enter
    this.setRenderComponent(nextProps);
  }
  // set render Component : ok or error
  setRenderComponent(props) {
    const ok = this.checkIsInstantiation(props.ok);
    const error = this.checkIsInstantiation(props.error);
    props.promise
afc163's avatar
afc163 committed
20 21
      .then(() => {
        this.setState({
22
          component: ok,
ddcat1115's avatar
ddcat1115 committed
23
        });
afc163's avatar
afc163 committed
24 25 26
      })
      .catch(() => {
        this.setState({
27
          component: error,
afc163's avatar
afc163 committed
28 29 30
        });
      });
  }
31 32 33 34 35 36 37 38 39 40
  // Determine whether the incoming component has been instantiated
  // AuthorizedRoute is already instantiated
  // Authorized  render is already instantiated, children is no instantiated
  // Secured is not instantiated
  checkIsInstantiation = (target) => {
    if (!React.isValidElement(target)) {
      return target;
    }
    return () => target;
  };
afc163's avatar
afc163 committed
41
  render() {
42 43 44
    const Component = this.state.component;
    return Component ? (
      <Component {...this.props} />
afc163's avatar
afc163 committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58
    ) : (
      <div
        style={{
          width: '100%',
          height: '100%',
          margin: 'auto',
          paddingTop: 50,
          textAlign: 'center',
        }}
      >
        <Spin size="large" />
      </div>
    );
  }
ddcat1115's avatar
ddcat1115 committed
59
}