try 动态加载SVG,但出现运行时错误,不确定问题出在哪里.有人能帮忙吗?

Component:

import React, { useEffect, useRef } from "react";
import { IIcon } from './IIcon';
import {
    DEFAULT_ASSET_ICON_FOLDER,
} from '@/constants/default';

function Icon({name}: IIcon) {
  const ImportedIconRef = useRef();

  useEffect(() => {
    const importIcon = async () => {
      try {
        ImportedIconRef.current = (
          await import(`${DEFAULT_ASSET_ICON_FOLDER}/${name}.svg`)
        ).ReactComponent;
      } catch (err) {
        // @TODO - Log error somewhere
      }
    };
    importIcon();
  }, [name]);

  const SvgIcon = ImportedIconRef.current;

  return (
    <SvgIcon />
  );
}

export default Icon;

Usage:

<Icon name="DELETE" />

Error

Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Icon`.

推荐答案

加载svg时,返回一个空/未定义的<SvgIcon />.

  1. 添加loading状态变量&;在finally块中更新.
const [, setLoading] = useState(false);
  useEffect(() => {
    setLoading(true);
    const importIcon = async () => {
      try {
        ImportedIconRef.current = (
          await import(`./${DEFAULT_ASSET_ICON_FOLDER}/${name}.svg`)
        ).ReactComponent;
      } catch (err) {
        // @TODO - Log error somewhere
        // console.log(err);
      } finally {
        setLoading(false);
      }
    };
    importIcon();
  }, [name]);
  1. 添加空判断
if (SvgIcon) {
    return <SvgIcon />;
  }
return null;

Edit practical-kilby-3h7iwn

Javascript相关问答推荐

使用脚本标签时的JSDoc智能感知

当我使用jQuery时,我的图标显示为[对象对象]

Python类实现的JavaScript吊坠是什么样子的?

带对角线分隔符的图像滑动器

如何在加载的元数据上使用juserc和await中获得同步负载?

Chrome是否忽略WebAuthentication userVerification设置?""

将2D数组转换为图形

JS—删除对象数组中对象的子对象

如何控制Reaction路由加载器中的错误状态?

VUE 3捕获错误并呈现另一个组件

不能将空字符串传递给cy.containes()

try 使用javascript隐藏下拉 Select

第二次更新文本输入字段后,Reaction崩溃

为什么我的按钮没有从&q;1更改为&q;X&q;?

传递方法VS泛型对象VS事件特定对象

Phaser3 preFX addGlow不支持zoom

使用RxJS from Event和@ViewChild vs KeyUp事件和RxJS主题更改输入字段值

无法检索与Puppeteer的蒸汽游戏的Bundle 包价格

判断函数参数的类型

使用API调用的VUE 3键盘输入同步问题