0

问题描述:

我已经开始使用开展一个项目。问题是,eslint 给了我一个关于似乎是正确声明的函数的意外错误


代码:

import React, { useState } from 'react';

type Props = {
  options: Array<string>
};

const Switch: React.FC<Props> = (props: Props) => {
  const [choice, setChoice] = useState<number>(0);

  // eslint gives error @ following function
  const handleSwitchChange = ():void => {
    choice + 1 >= options.length ? setChoice(0) : setChoice(choice + 1)
  };

  return (
    <div>{options[choice]}</div>
    <button onClick={handleSwitchChange}>Change choice</button>
  );
};

更多详细信息:

现在这可以按预期工作,但尽管我传递给的函数是声明类型voideslint 给我以下错误:

期望一个赋值或函数调用,而是看到一个表达式。

现在我不想只是禁用规则,但我看不出代码有任何固有的错误。有什么方法可以正确编写函数,这样 es-lint 就不会抱怨了吗?


ESLint 错误(额外信息)

引发错误的特定 eslint 模块

 {
    "resource": "<PATH CENSORED>/src/components/forms/Switch.tsx",
    "owner": "eslint",
    "code": "@typescript-eslint/no-unused-expressions",
    "severity": 8,
    "message": "Expected an assignment or function call and instead saw an expression.",
    "source": "eslint",
    "startLineNumber": 12,
    "startColumn": 5,
    "endLineNumber": 12,
    "endColumn": 85
}
4

1 回答 1

2

当你有一个带花括号的箭头函数时,它的主体必须至少包含一个语句(如错误消息所示,一个赋值或函数调用,或者一个iforreturn语句或类似的东西):

const handleSwitchChange = {
  // Statements must go here
};

您实际上已经给出了一个表达式(除了类型检查之外)可能出现在赋值或函数参数的右侧:

// Syntactically valid, not necessarily meaningful
const hypothetical = choice + 1 >= options.length ? setChoice(0) : setChoice(choice + 1);
someFunction(choice + 1 >= options.length ? setChoice(0) : setChoice(choice + 1));

你有几个选择。最简单的方法是通过删除花括号将箭头函数更改为采用表达式的形式

const handleSwitchChange = (): void =>
  choice + 1 >= options.length ? setChoice(0) : setChoice(choice + 1);

有多种方法可以将其重构为更像语句,例如用语句替换三元运算符if,或者将函数移至顶层。

// Equally valid with or without curly braces
// (Curly braces explicitly ignore the return value)
const handleSwitchChange = (): void => {
  setChoice(choice + 1 >= options.length ? 0 : choice + 1);
};
于 2019-12-22T12:38:16.290 回答