简体   繁体   English

每个 React 类方法的“缺少函数返回类型”

[英]"Missing return type on function" for every React class method

I a stateful React component in my Typescript project.我的 Typescript 项目中有一个有状态的 React 组件。 I lint it with ESLint using @typescript-eslint/parser and @typescript-eslint/eslint-plugin .我使用@typescript-eslint/parser typescript @typescript-eslint/parser@typescript-eslint/eslint-plugin用 ESLint lint 它。 I've enabled the rule @typescript-eslint/explicit-function-return-type .我启用了规则@typescript-eslint/explicit-function-return-type

My component looks similar to this:我的组件看起来类似于:

interface Props = {
  name: string;
}

interface State = {
  score: number
}

class Person extends Component<Props, State> {
  state = {
    score: 2,
  };

  componentDidMount() {
    ...
  }

  render() {
    ...
  }
}

In the above component I get the ESLint error on the componentDidMount and render methods:在上面的组件中,我在componentDidMountrender方法上得到了 ESLint 错误:

Missing return type on function - @typescript-eslint/explicit-function-return-type

I quite like the lint rule in general, but surely I don't have to declare a return type for all these React methods.总的来说,我非常喜欢 lint 规则,但我肯定不必为所有这些 React 方法声明返回类型。 I have @types/react and @types/react-dom installed, so aren't these return types covered already?我已经安装了@types/react@types/react-dom ,所以这些返回类型不是已经涵盖了吗?

Try writing the return type for render function as尝试将渲染函数的返回类型写为

render(): JSX.Element {
  // render code
}

This works for me!这对我有用!

I just got it working by adding the rule into .eslintrc.json with我只是通过将规则添加到.eslintrc.json来让它工作

{ "allowTypedFunctionExpressions": true }

.eslintrc.json .eslintrc.json

{
  "parser": "@typescript-eslint/parser",
  "extends": ["plugin:@typescript-eslint/recommended"],
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      { "allowTypedFunctionExpressions": true }
    ]
  }
}

versions版本

"@typescript-eslint/eslint-plugin": "^1.10.2",
"@typescript-eslint/parser": "^1.10.2",
"eslint": "^6.0.0",

I could be wrong here as I have not personally used @typescript-eslint/explicit-function-return-type but it's name sounds as if you need a return in every single function written, including the lifecycle methods.我在这里可能是错的,因为我没有亲自使用@typescript-eslint/explicit-function-return-type但它的名字听起来好像你需要在每个编写的函数中return ,包括生命周期方法。 Remember that the ESLint and React are not the same.请记住,ESLint 和 React 是不一样的。 ESLint is simply running over your code to point out potential errors. ESLint 只是运行你的代码来指出潜在的错误。 The React library should still be able to run without issue if you do not include these return statements如果不包含这些return语句,React 库应该仍然能够正常运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM