PromiseRender.js 1.85 KB
Newer Older
ddcat1115's avatar
ddcat1115 committed
1
import { Spin } from 'antd';
2 3 4
import isEqual from 'lodash/isEqual';
import React from 'react';
import { isComponentClass } from './Secured';
ddcat1115's avatar
ddcat1115 committed
5

6
export default class PromiseRender extends React.Component {
afc163's avatar
afc163 committed
7
  state = {
8
    component: null,
afc163's avatar
afc163 committed
9
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
10

11
  componentDidMount() {
12 13
    this.setRenderComponent(this.props);
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
14

15 16 17 18 19 20 21 22
  shouldComponentUpdate = (nextProps, nextState) => {
    const { component } = this.state;
    if (!isEqual(nextProps, this.props)) {
      this.setRenderComponent(nextProps);
    }
    if (nextState.component !== component) return true;
    return false;
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
23

24 25 26 27 28
  // 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
29 30
      .then(() => {
        this.setState({
31
          component: ok,
ddcat1115's avatar
ddcat1115 committed
32
        });
afc163's avatar
afc163 committed
33 34 35
      })
      .catch(() => {
        this.setState({
36
          component: error,
afc163's avatar
afc163 committed
37 38 39
        });
      });
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
40

41 42 43 44
  // 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
45
  checkIsInstantiation = target => {
46 47 48 49 50 51
    if (isComponentClass(target)) {
      const Target = target;
      return props => <Target {...props} />;
    }
    if (React.isValidElement(target)) {
      return props => React.cloneElement(target, props);
52 53 54
    }
    return () => target;
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
55

afc163's avatar
afc163 committed
56
  render() {
57 58 59 60
    const { component: Component } = this.state;
    const { ok, error, promise, ...rest } = this.props;
    return Component ? (
      <Component {...rest} />
afc163's avatar
afc163 committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74
    ) : (
      <div
        style={{
          width: '100%',
          height: '100%',
          margin: 'auto',
          paddingTop: 50,
          textAlign: 'center',
        }}
      >
        <Spin size="large" />
      </div>
    );
  }
ddcat1115's avatar
ddcat1115 committed
75
}