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
  };
陈帅's avatar
陈帅 committed
8

9
  componentDidMount() {
10 11
    this.setRenderComponent(this.props);
  }
陈帅's avatar
陈帅 committed
12

13 14 15 16
  componentWillReceiveProps(nextProps) {
    // new Props enter
    this.setRenderComponent(nextProps);
  }
陈帅's avatar
陈帅 committed
17

18 19 20 21 22
  // 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
23 24
      .then(() => {
        this.setState({
25
          component: ok,
ddcat1115's avatar
ddcat1115 committed
26
        });
afc163's avatar
afc163 committed
27 28 29
      })
      .catch(() => {
        this.setState({
30
          component: error,
afc163's avatar
afc163 committed
31 32 33
        });
      });
  }
陈帅's avatar
陈帅 committed
34

35 36 37 38
  // 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
jim's avatar
jim committed
39
  checkIsInstantiation = target => {
40 41 42 43 44
    if (!React.isValidElement(target)) {
      return target;
    }
    return () => target;
  };
陈帅's avatar
陈帅 committed
45

afc163's avatar
afc163 committed
46
  render() {
陈帅's avatar
陈帅 committed
47
    const { component: Component } = this.state;
48 49
    return Component ? (
      <Component {...this.props} />
afc163's avatar
afc163 committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63
    ) : (
      <div
        style={{
          width: '100%',
          height: '100%',
          margin: 'auto',
          paddingTop: 50,
          textAlign: 'center',
        }}
      >
        <Spin size="large" />
      </div>
    );
  }
ddcat1115's avatar
ddcat1115 committed
64
}