如何解决React中Left side of comma operator is unused and has no side effects.ts(2695)错误?
错误原因与解决方法:Left side of comma operator is unused and has no side effects.ts(2695)
错误原因
你在自定义Hook的return语句里用了错误语法:
- 给
industryStateValue加了无意义的星号包裹 - 误用逗号运算符,导致TypeScript判定逗号左侧的表达式(被错误标记的
industryStateValue)既没被使用,也没有产生任何副作用,因此抛出该错误。
你的本意应该是返回Hook的状态值和操作方法,但当前写法完全不符合JavaScript/TypeScript的语法规范。
解决方法
根据需求,有两种规范的返回方式可选:
方式一:返回对象(推荐,可读性更强)
修改return部分代码为:
return { industryStateValue, onJoinOrLeaveIndustry };
外部使用该Hook时,可通过对象解构获取内容:
const { industryStateValue, onJoinOrLeaveIndustry } = useIndustryData();
方式二:返回数组(适合需要按顺序解构的场景)
修改return部分代码为:
return [industryStateValue, onJoinOrLeaveIndustry];
外部使用该Hook时,可通过数组解构获取内容:
const [stateValue, handleJoinLeave] = useIndustryData();
注意删除原代码里无用的星号和错误的逗号运算符写法。
内容的提问来源于stack exchange,提问作者Innocent Oyebode
相关产品推荐
相关产品推荐

