【问题标题】:How can I fix ES6 Eslint errors while trying to return a ternary operator in arrow function?尝试在箭头函数中返回三元运算符时如何修复 ES6 Eslint 错误?
【发布时间】:2019-01-22 00:47:49
【问题描述】:

我知道() => {} 不需要返回,但是如果它不存在,那么Eslint 会抱怨未使用的表达式。

export const isInInterval = (from, to, target) => {
  if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
    return
  }
  const toUnixTimestamp = time => new Date(time).getTime()
  toUnixTimestamp(to) - target > toUnixTimestamp(from) ? true : false
}

这里是函数:它试图找出某个指定的日期(to)减去指定的时间段(target)是否比from晚。如果是这样,它应该返回 true,在相反的情况下返回 false。 我一直遇到 eslint 错误expected assignment to a function call and instead saw expression。

我尝试重写了几次,但在大多数迭代中我得到了`箭头函数期望没有返回错误,例如:

return (toUnixTimestamp(to) - 目标 > toUnixTimestamp(from)) ?真:假

【问题讨论】:

  • 很难看出发生了什么,因为你的代码太紧凑了!我会添加更多中间变量以更好地了解正在发生的事情。短而紧凑的一行代码不会提高代码的可读性。简单明了的代码提高了可读性。
  • 根据@givanse 的评论,您可以考虑像isDateValid 这样的函数,然后您的第一行可以是if (!isDateValid(to) || !isDateValid(from)) return;

标签: javascript ecmascript-6 eslint ternary-operator


【解决方案1】:

我明白 () => {} 不需要返回

事实并非如此。只有当=> 后面是单个表达式时,箭头函数才会隐式返回。如果您使用=> {,则左括号{ 表示功能块的开始,并且您确实需要在块的末尾显式地return(或者您想要return 的任何其他地方)。

目前,您的代码根本没有返回任何内容 - 这就是 linting 错误试图告诉您的 - true : false 目前未使用,它只是一个孤立的表达式。

因此,只需将 return 语句添加到条件的开头即可:

export const isInInterval = (from, to, target) => {
  if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
    return
  }
  const toUnixTimestamp = time => new Date(time).getTime()
  return toUnixTimestamp(to) - target > toUnixTimestamp(from)
    ? true
    : false
}

或者,因为> 已经计算为boolean,您可以完全省略条件运算符:

return toUnixTimestamp(to) - target > toUnixTimestamp(from)

这是一个示例,说明如何编写一个确实使用隐式返回的箭头函数:

export const isEarlyTimestamp = (timestamp) => (
  timestamp < 4000000
  ? true
  : false
);

【讨论】:

  • 谢谢CertainPerformance,eslint 再次用arrow function expected no return value 对我尖叫,我想我会忽略 eslint-disable-line 行。
  • 让你绊倒的规则可能是consistent-return:eslint.org/docs/rules/consistent-return 如果你喜欢尽可能隐式返回(我认为这很好——它显着减少了语法噪音,尤其是使用数组方法),只需禁用该规则。
【解决方案2】:

试试这个:

export const isInInterval = (from, to, target) => {
    if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
    return false
    }
    const toUnixTimestamp = time => new Date(time).getTime()
    return toUnixTimestamp(to) - target > toUnixTimestamp(from);
}

【讨论】:

  • 谢谢,Tilak,我也想到了,可惜我还是得到了[eslint] Unnecessary use of boolean literals in conditional expression. (no-unneeded-ternary)。
  • 好吧,做一件事。写一个 if 条件语句而不是三元并检查一次!
  • 确实有帮助!谢谢!虽然它看起来有点不优雅,但我想知道它是否可以做得更好: if (toUnixTimestamp(to) - target > toUnixTimestamp(from)) { return true } return false 但是它是唯一适用于所有 eslint 的方法建议的解决方案。谢谢
  • 同样,true 上的错误:[eslint] 在条件表达式中不必要地使用布尔文字。 (no-unneeded-ternary),重写为 if - else 有帮助。
  • 再试一次,这样会更好!!
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 2018-07-24
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2018-06-15
相关资源
最近更新 更多