You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React+TypeScript中使用useMemo返回两个值?

React + TypeScript中useMemo返回双值的报错修复

问题背景

原本通过独立函数renderText根据text和isAvailable参数生成对应的图标、颜色及UI,现在尝试将逻辑移入组件内的useMemo钩子,直接返回icon和color后在组件内渲染JSX,但运行时出现报错:cannot destructure property 'icon' of useMemo(...) as it is undefined。

报错原因

  • 回调函数无默认返回值:当text既不是'N/A'也不是'text-1'时,useMemo的回调函数没有返回任何值,默认返回undefined,此时解构{icon, color}就会抛出错误。
  • 依赖数组不完整:useMemo的依赖列表只添加了text,但逻辑中用到了isAvailable参数,会导致缓存的icon和color不会随isAvailable的变化而更新,引发逻辑错误。
  • 语法错误:else if代码块末尾多写了一个逗号,导致函数语法不合法,间接引发执行异常。

修复方案

  1. 为useMemo的回调函数添加默认返回值,确保无论text是什么值,函数都能返回包含icon和color的对象;
  2. 补全useMemo的依赖数组,将isAvailable加入其中,保证缓存值能随依赖变化更新;
  3. 修正语法错误,删除else if块末尾的多余逗号。

完整修复代码

const Component: React.FC<ComponentProps> = ({ text, isAvailable }) => {
    const { icon, color } = React.useMemo(() => {
        let icon: IconName | undefined = undefined;
        let color: StatusColor | undefined = undefined;

        if (text === 'N/A') {
            icon = 'icon1';
            color = 'gray';
        } else if (text === 'text-1') {
            icon = isAvailable ? 'icon2' : 'icon3';
            color = isAvailable ? 'blue' : 'orange';
        }
        // 确保所有分支都返回对象,避免undefined
        return { icon, color };
    }, [text, isAvailable]); // 补全依赖项isAvailable

    return (
        <>
            {icon && <Icon name={icon} color={color} />}
            <span>{text}</span>
        </>
    );
};

内容的提问来源于stack exchange,提问作者Harika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:07:02