代码之家  ›  专栏  ›  技术社区  ›  wsfuller

ESLint在类组件中缺少props验证

  •  1
  • wsfuller  · 技术社区  · 7 年前

    查看 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的行为与预期一致。但是,当将同一方法应用于类组件时,无法验证数据。我认为这可能是某种类型的范围界定问题,但我尝试的所有“数据”都没有得到验证。看了很多例子,似乎道具的声明是正确的,但也许我忽略了什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   wsfuller    7 年前

    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错误。