【问题标题】:ESLint missing props validation in Class ComponentESLint 在类组件中缺少道具验证
【发布时间】:2017-11-23 06:48:44
【问题描述】:

查看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 的行为符合预期。但是,当将相同的方法应用于类组件时,无法验证数据。我认为这可能是某种范围界定问题,但我尝试过的所有“数据”都没有得到验证。浏览了很多示例,看来道具已正确声明,但也许我忽略了一些东西?

【问题讨论】:

    标签: javascript reactjs eslint react-proptypes


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2016-12-05
      • 2019-11-18
      • 2021-09-04
      • 2017-09-26
      • 2020-11-12
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多