如何在 Flowtype 中键入此组件

How to type this component in Flowtype

我在 React 中有这个组件,它使用 import() 动态加载另一个组件。该组件基于此博客 post https://tylermcginnis.com/react-router-code-splitting/


    // @flow

    import * as React from 'react';

    type Props = { 
       load: () => Promise<any> 
    };

    type State = {
        component: ?React.Element<any>,
    };

    export default class DynamicImport extends React.Component<Props, State> {
      state = {
          component: null,
      };

      componentWillMount() {
        this.props
            .load()
            .then(component => {
                this.setState(() => ({
                   component: component.default ? component.default : component,
                }));
             })
             .catch(err => {
                 console.log(err);
             });
        }

      render() {
        if (Boolean(this.state.component) === false) {
          return <div>Loading..</div>;
        } else {
          const Component: Class<any> = this.state.component;
          return <Component {...this.props} />;
        }
      }
    }

我是这样用的:<DynamicImport load={() => import('./path/to/Component')}/>

我也在使用 Flowtype 对项目进行类型检查,我的问题是如何输入此组件,我不断收到有关初始状态为 null 的错误。

Cannot assign this.state.component to Component because:
• null or undefined [1] is incompatible with statics of any [2].
• React.Element [3] is incompatible with statics of any [2].
• null [4] is incompatible with statics of any [2].

[1][3]  9│       component: ?React.Element<any>,
         :
   [4] 14│         component: null,
         :
       31│         if (Boolean(this.state.component) === false) {
       32│           return <div>Loading..</div>;
       33│         } else {
   [2] 34│           const Component: Class<any> = this.state.component;
       35│           return <Component {...this.props} />;
       36│         }
       37│       }

你需要使用React.ComponentType<>来定义React组件的类型。

此外,您确定组件 属性 是否已设置的细化未被流识别,因此它错误地指出它可能为空。

(Try)

// @flow

import * as React from 'react';

type Props = { 
   load: () => Promise<any> 
};

type State = {
    component: ?React.ComponentType<Props>,
};

export default class DynamicImport extends React.Component<Props, State> {
  state = {
      component: null,
  };

  componentWillMount() {
    this.props
        .load()
        .then(component => {
            this.setState(() => ({
               component: component.default ? component.default : component,
            }));
         })
         .catch(err => {
             console.log(err);
         });
    }

  render() {
    if (!this.state.component) {
      return <div>Loading..</div>;
    } else {
      const Component: React.ComponentType<Props> = this.state.component;
      return <Component {...this.props} />;
    }
  }
}