ESLint在类组件中缺少道具验证

时间:2017-11-22 19:50:33

标签: javascript reactjs eslint react-proptypes

查看official typechecking docs并且由于某种原因,ESLint在验证解构属性时会抛出错误。

工作功能组件

import React from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'react-apollo';

function MyComponentContainer(props) {
  const { data: { loading, error, user } } = props;
  if (loading) { return ( <Loader/> ); }
  if (error) { return ( <Error /> ); }
  return <MyComponent />;
}

MyComponentContainer.propTypes = {
  data: PropTypes.shape({}),
};

MyComponentContainer.defaultProps = {
  data: {},
};

export graphql(...)(...)

错误类组件

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'react-apollo';

function MyComponentContainer extends Component{
  constructor(){...}
  const { data: { loading, error, user }} = this.props; <<<<<<< 'data' is missing in props validation
  render(){
    if (loading) { return ( <Loader/> ); }
    if (error) { return ( <Error /> ); }
    return <MyComponent />;
  }

}

MyComponentContainer.propTypes = {
  data: PropTypes.shape({}),
};

MyComponentContainer.defaultProps = {
  data: {},
};

export graphql(...)(...)

.eslintrc

{
  "extends": "airbnb",
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
        "jsx": true,
        "modules": true,
        "experimentalObjectRestSpread": true
    }
  },
  "env":{
    "browser": true,
    "jest": true
  },
  "plugins": [
    "react",
    "jsx-a11y",
    "import",
    "jest"
  ],
  "rules": {
    "no-tabs": 0,
    "no-mixed-spaces-and-tabs": 0,
    camelcase: ["error", {properties: "never"}],
    "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
    "jsx-a11y/anchor-is-valid": [ "error", {
        "components": [ "Link" ],
        "specialLink": [ "to" ],
        "aspects": [ "noHref", "invalidHref", "preferButton" ]
      }]
  }
}

在功能组件中,ESLint的行为符合预期。但是,将相同的方法应用于类组件时,无法验证数据。我认为这可能是某种类型的范围界定问题,但我尝试过的所有内容都是数据&#39;没有得到验证。看了几个例子,看来道具正在被宣布正确,但也许我忽略了一些东西?

1 个答案:

答案 0 :(得分:0)

好的,找到了需要声明的另一个例子。

ESLint React Plugin Docs

function MyComponentContainer extends Component{
  static propTypes = {
    data: PropTypes.shape({}),
  };

  static defaultProps = {
    data: {},
  };

  constructor(){...}
  const { data: { loading, error, user }} = this.props;
  render(){
    if (loading) { return ( <Loader/> ); }
    if (error) { return ( <Error /> ); }
    return <MyComponent />;
  }
}

注意:propTypes需要在constructor之前声明,否则会引发另一个Lint错误。