如何使用 eslint-plugin-react 修复由 Flow Function Types 引起的警告?

How to fix warning caused by Flow Function Types using eslint-plugin-react?

我在我的 React 组件的以下行中收到警告

handleToggle: Function;

我正在使用 eslint-plugin-react and Flow,但收到警告 "handleToggle should be placed after constructor"。这与规则 react/sort-comp 有关。我在 .eslintrc.json

上尝试了以下内容
 "react/sort-comp": [1, {
  "order": [
    "static-methods",
    "lifecycle",
    "everything-else",
    "render"
  ],
  "groups": {
    "lifecycle": [
      "displayName",
      "propTypes",
      "contextTypes",
      "childContextTypes",
      "/^.*: Function$/",
      "mixins",
      "statics",
      "defaultProps",
      "state",
      "constructor",
      "getDefaultProps",
      "getInitialState",
      "getChildContext",
      "componentWillMount",
      "componentDidMount",
      "componentWillReceiveProps",
      "shouldComponentUpdate",
      "componentWillUpdate",
      "componentDidUpdate",
      "componentWillUnmount"
    ]
  }
}]

但我无法修复警告。我希望构造函数之前的函数类型与其他类型定义相同。我怎样才能做到这一点?

问题是 eslint-plugin-react 不知道 Flow,所以 "type definitions" 没有组。您可以通过将 "everything-else" 移动到组件的顶部(在 "static-methods" 之前)使 eslint 允许您将类型定义放在组件的开头,但这也将允许您定义任何函数或实例变量(如果您正在使用它们)在 constructor

之前

即,将您的 .eslintrc.json 更改为:

 "react/sort-comp": [1, {
  "order": [
    "everything-else",
    "static-methods",
    "lifecycle",
    "render"
  ],
  "groups": { /* ... */ }
 }]

您现在可以将 "new" 项 (type-annotations)* 添加到配置中的订单部分:

"react/sort-comp": [
  2,
  {
    "order": [
      "type-annotations",  // <-- this is "new"
      "static-methods",
      "lifecycle",
      "everything-else",
      "render"
    ],
    "groups": {
      "lifecycle": [
        "displayName",
        "propTypes",
        "contextTypes",
        "childContextTypes",
        "mixins",
        "statics",
        "defaultProps",
        "constructor",
        "getDefaultProps",
        "state",
        "getInitialState",
        "getChildContext",
        "getDerivedStateFromProps",
        "componentWillMount",
        "UNSAFE_componentWillMount",
        "componentDidMount",
        "componentWillReceiveProps",
        "UNSAFE_componentWillReceiveProps",
        "shouldComponentUpdate",
        "componentWillUpdate",
        "UNSAFE_componentWillUpdate",
        "getSnapshotBeforeUpdate",
        "componentDidUpdate",
        "componentDidCatch",
        "componentWillUnmount"
      ]
    }
  }
]

之后,eslint 将停止抱怨。

* 在此处找到:https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md#rule-options