You need to enable JavaScript to run this app. TypeScript环境下如何更新含数组结构对象的useState状态
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript环境下如何更新含数组结构对象的useState状态

报错原因

你代码里的三元判断条件写错了:你写的[category]是创建了一个包含category值的数组,只要category非空这个数组永远为真值,所以不管selectedInterest中是否存在对应分类键,都会执行selectedInterest[category].concat(keyValue)逻辑。当分类不存在时selectedInterest[category]为undefined,调用concat自然抛出该错误。

正确实现代码

推荐使用状态更新函数的写法,避免依赖外部状态带来的闭包问题,同时兼容TypeScript类型校验:

type selectedInterestType = {
  [category: string]: string[];
};

// 补充Props类型定义
type Props = {
  category: string;
  keyValue: string;
  // 如果你用到了value.kr可以在这里补充对应字段,原代码此处有笔误,没有定义value变量
}

const InterestBtn = ({ category, keyValue }: Props) => {
  const [selectedInterest, setSelectedInterest] = useState<selectedInterestType>({});

  const onInterestClick = () => {
    setSelectedInterest(prev => {
      // 先取之前的分类数组,不存在就用空数组兜底
      const currentCategoryList = prev[category] ?? [];
      return {
        ...prev,
        // 追加新的keyValue
        [category]: [...currentCategoryList, keyValue]
      }
    });
  };
  
  return (
    <button onClick={onInterestClick}>
      {/* 原代码这里的value变量未定义,如果你要展示keyValue的对应中文可以改为传入对应的字段,比如keyValueLabel */}
      <p>{keyValue}</p>
    </button>
  );
};
可选优化:避免重复添加相同keyValue

如果需要防止同一个分类下重复添加相同的keyValue,可以在更新数组前做判断:

[category]: currentCategoryList.includes(keyValue) 
  ? currentCategoryList 
  : [...currentCategoryList, keyValue]

内容的提问来源于stack exchange,提问作者김일혁

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 08:24:03