使用Typescript AsyncComponent在React中加载延迟路径

时间:2017-11-01 14:57:34

标签: reactjs typescript lazy-loading react-router-v4 dynamic-import

我试图通过实现AsyncCompoment类(在此处记录Code Splitting in Create React App)来在React中延迟加载路由。下面是教程中的es6 asyncComponent函数:

import React, { Component } from "react";

    export default function asyncComponent(importComponent) {
      class AsyncComponent extends Component {
        constructor(props) {
          super(props);

          this.state = {
            component: null
          };
        }

        async componentDidMount() {
          const { default: component } = await importComponent();

          this.setState({
            component: component
          });
        }

        render() {
          const C = this.state.component;

          return C ? <C {...this.props} /> : null;
        }
      }

      return AsyncComponent;
    }

我已经在打字稿中写了这个函数,并且可以确认组件确实是懒惰加载的。我面临的问题是它们没有被渲染。我能够确定组件对象在componentDidMount钩子中始终未定义:

//AsyncComponent.tsx
async componentDidMount() {
              const { default: component } = await importComponent();

              this.setState({
                component: component
              });
            }

从importComponent函数返回的对象具有以下属性:

{
MyComponent: class MyComponent: f,
__esModule: true
}

我修改了componentDidMount方法以获取此对象的第一个属性,即MyComponent类。在此更改之后,我的项目现在延迟加载组件并正确呈现它们。

async componentDidMount() {
          const component = await importComponent();

          this.setState({
            component: component[Object.keys(component)[0]]
          });
        }

我最好的猜测是我没有在打字稿中正确写出这一行:

const { default: component } = await importComponent();

我像这样调用asyncComponent方法:

const MyComponent = asyncComponent(()=>import(./components/MyComponent));

任何人都知道如何在打字稿中实现AsyncComponent?我不确定是否只是在esModule对象上获取0索引是正确的方法。

1 个答案:

答案 0 :(得分:5)

想出来,所需要的只是在我想要延迟加载的所有Component类上导出默认值。这是我的完整解决方案:

//AsyncComponent.tsx
import * as React from "react";

interface AsyncComponentState{
    Component: any;
}
export default function asyncComponent(getComponent: any): any  {
    class AsyncComponent extends React.Component<{},AsyncComponentState> {


        constructor(props: any) {
            super(props);

            this.state = {
                Component: null
            };
        }

        async componentDidMount(){
            const {default: Component} = await getComponent();
            this.setState({
                Component: Component
            });


        }


        render() {
            const C = this.state.Component;
            return C ? <C {...this.props}/> : <div>....Loading</div>
        }
    }
    return AsyncComponent;

}
//Counter.tsx
import * as React from 'react';
import { RouteComponentProps } from 'react-router';

interface CounterState {
    currentCount: number;
}

 class Counter extends React.Component<RouteComponentProps<{}>, CounterState> {
    constructor() {
        super();
        this.state = { currentCount: 0 };
    }

    public render() {
        return <div>
            <h1>Counter</h1>

            <p>This is a simple example of a React component.</p>

            <p>Current count: <strong>{ this.state.currentCount }</strong></p>

            <button onClick={ () => { this.incrementCounter() } }>Increment</button>
        </div>;
    }

    incrementCounter() {
        this.setState({
            currentCount: this.state.currentCount + 1
        });
    }
}
export default Counter;

//routes.tsx
import * as React from 'react';
import {Route} from 'react-router-dom';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import asyncComponent from './components/AsyncComponent';


const AsyncCounter =  asyncComponent(() =>  import('./components/Counter'));

export const routes = <Layout>
    <Route exact path='/' component={ Home } />
    <Route path='/counter' component={ AsyncCounter } />
</Layout>;