[英]ESLint missing props validation in Class Component
查看官方的typechecking文檔 ,出於某種原因,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在功能組件中的行為符合預期。 但是,將相同的方法應用於類組件時,無法驗證數據。 我以為這可能是某種范圍界定問題,但是我嘗試過的所有“數據”都沒有得到驗證。 看了很多例子,似乎道具被正確地聲明了,但也許我忽略了一些東西?
好的,在需要聲明的地方找到另一個示例。
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錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.