首页 > 解决方案 > “ExoticComponent”类型上不存在属性 ***

问题描述

我尝试在 React / Next.js 项目中进行代码拆分,但面临障碍。

我在这里遵循操作方法:https ://reactjs.org/docs/code-splitting.html

在这里导入:

const { SHA512 } = React.lazy(() => import("crypto-js"));

并在useEffect这里使用:

useEffect(() => {
    setTimeout(() => {
      let window2: any = window;
      if (window2.bp && process.env.NEXT_PUBLIC_BARION_ID) {
        const { totalPriceInt, unitPriceInt } = calcUnitAndTotalPrice(
          startPaymentIn,
          buyTicketData
        );
        window2.bp("track", "initiateCheckout", {
          contentType: "Product",
          currency: "HUF",
          id: startPaymentIn.eventId,
          name: buyTicketData?.name,
          quantity: startPaymentIn.quantity ?? 1.0,
          unit: "db",
          imageUrl: `https://ticket-t01.s3.eu-central-1.amazonaws.com/${buyTicketData?.imgId}_0.cover.jpg`,
          list: "ProductPage",
        });
        window2.bp("track", "setUserProperties", {
          userId: SHA512(getTempUserId(localStorage)).toString(), // <--- HERE
        });
      }
    }, 4000);
  }, []);

但得到这个错误:

./components/LoginAndRegistration.tsx:25:9
Type error: Property 'SHA512' does not exist on type 'ExoticComponent<any> & { readonly _result: ComponentType<any>; }'.

  23 | import { GoogleLogin } from "react-google-login";
  24 | import axios from "axios";
> 25 | const { SHA512 } = React.lazy(() => import("crypto-js"));
     |         ^
  26 | 
  27 | interface LoginAndRegistrationProps {
  28 |   isRegistration: boolean;
error Command failed with exit code 1.

你知道为什么它是错的吗?

在没有延迟加载的情况下工作之前:

import { SHA512 } from "crypto-js";

我还尝试了 Next.js 解决方法:

import dynamic from "next/dynamic";
const { SHA512 } = dynamic(() => import("crypto-js"));

但收到此错误:

Type error: 'await' expressions are only allowed within async functions and at the top levels of modules.

  130 | 
  131 |   useEffect(() => {
> 132 |     const { SHA512 } = await import("crypto-js");
      |                        ^
  133 |     setTimeout(() => {
  134 |       let window2: any = window;
  135 |       if (window2.bp && process.env.NEXT_PUBLIC_BARION_ID) {

标签: reactjsnext.jscode-splitting

解决方案


正如这里提到的,

React.lazy接受一个必须调用动态的函数import()。这必须返回一个Promise 解析为具有default包含 React 组件的导出的模块。

所以你不能使用React.lazy这个crypto-js包,因为它不导出 React 组件。

您可以在 NextJS中使用动态导入。像这样:

useEffect(() => {
  import('crypto-js').then(({ SHA512 }) => {
    // Use SHA512 here
  });
}, []);

推荐阅读