ESLint报错Expected an assignment or function call and instead saw an expression求助
ESLint报错Expected an assignment or function call and instead saw an expression求助
嘿,这个问题我之前排查过好多次,咱们来拆解一下你的代码问题在哪~
首先,ESLint报这个错是触发了no-unused-expressions规则,意思是你写了孤立的表达式——这些表达式既没有被赋值给变量,也没有被作为函数返回值,完全没产生实际作用,ESLint会认为这是无效代码。
看你的代码:
- 在
if和else if分支里,你调用了currentDate.toLocaleDateString(),但没有把这个方法返回的格式化日期结果存起来或者return出去,相当于白调用了; - 最下面的
else分支里,('invalid country code')只是一个字符串字面量表达式,既没赋值也没输出,完全是无用代码。
解决方法很简单,只要让这些表达式的结果被使用就行,最直接的方式就是给每个分支加上return(毕竟你的函数是用来格式化日期的,肯定要返回结果对吧),修改后的代码如下:
export function formatDate(country) { const currentDate = new Date(); const options = { year: 'numeric', month: 'numeric', day: 'numeric' }; if (country === 'US') { return currentDate.toLocaleDateString('en-US', options); } else if (['UK','DE', 'AU'].includes(country)) { return currentDate.toLocaleDateString('en-GB', options); } else { // 这里可以根据需求选择返回错误信息,或者抛出错误 return 'invalid country code'; // 如果需要更严格的错误提示,可以换成抛出错误: // throw new Error('invalid country code'); } }
不需要用三元表达式哦,你的分支逻辑用if-else完全没问题,只要确保每个分支的表达式都被合理使用(比如return出去),就能解决这个ESLint报错啦。
备注:内容来源于stack exchange,提问作者ericoder
相关产品推荐
相关产品推荐

