1

在我们的项目中,我们有大约 10 个使用 react-lottie 库并加载了可加载组件库的动画。其中一些动画在 Gatsby 开发环境中崩溃。我已经设法缩小了哪些失败的范围,并且有 2 个。

该组件是这样构建的:

@LottieComponent.tsx
import React, { CSSProperties } from 'react';
import Lottie from 'lottie-react';
import json from './lottieAnimation.json';

interface Props {
  styles?: CSSProperties;
}

export default ({ styles }: Props) => (
  <Lottie style={styles} animationData={json} />
);

然后我们使用代码拆分:

@index.tsx

import loadable from '@loadable/component';

const ExchangeInfographic = loadable(
  () => import('./animationComponents/ExchangeGraphic')
);

export {
  ExchangeInfographic
};

然后我们将组件导入到模块中,如下所示:

import { ExchangeInfographic } from '../../components/Infographic';

const ExampleComponent = () => {
  const [animationWasRendered, setAnimationWasRendered] = useState(false);
  return (
    <ReactVisibilitySensor
      onChange={(isVisible) => {
        isVisible && setAnimationWasRendered(true);
      }}
      partialVisibility
    >
      <SectionCustomComponent>
        <Container>
            <Col>
              {animationWasRendered ? <ExchangeInfographic /> : <></>}
            </Col>
          </Row>
        </Container>
      </Section>
    </ReactVisibilitySensor>
  );
};
export default ExampleComponent;

我在控制台中得到的错误是:

react-dom.development.js:23966 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `InnerLoadable`.

我检查了此错误消息的可能原因并找到了此线程: https ://github.com/facebook/react/issues/13445 和 代码拆分/react-loadable 问题

但看起来动态导入不会失败。令人困惑的部分是,为什么它只会在某些动画上崩溃而其他每次都可以正常工作。哦

你知道我错过了什么吗?

感谢您的任何建议!

4

2 回答 2

0

我不确定它是否能解决问题,因为我不知道所有规格或您的用例,但这export对我来说似乎很奇怪:

@index.tsx

import loadable from '@loadable/component';

const ExchangeInfographic = loadable(
  () => import('./animationComponents/ExchangeGraphic')
);

export {
  ExchangeInfographic
};

您是否尝试过类似的方法:

@index.tsx

import loadable from '@loadable/component';

const ExchangeInfographic = loadable(
  () => import('./animationComponents/ExchangeGraphic')
);

export ExchangeInfographic
于 2021-02-02T15:41:09.537 回答
0

所以几个月后,我决定再次尝试解决这个奇怪的错误。

问题说明:

ExchangeInfographic 反应组件有一个像这样的文件名ExchangeInfographic.tsx

包含抽奖动画的 json 的 json 文件有一个像这样的文件名exchangeInfographic.json

由于某种原因,在像这样导入组件后,json文件和react组件文件的名称相同(react组件的大写字母除外)

import {ExchangeInfographic} from 'path to the file;'

它将返回一个对象而不是函数。

为了修复它,我只是将 json 所在的文件的名称更改为例如exchange.json

这是一种魔法。这是一种maaagiiic...

于 2021-08-25T12:18:52.297 回答