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,提问作者김일혁
相关产品推荐
相关产品推荐

