ESLint - the component should be written as a pure function (respond to preference / stateless function)

ESLint gives me this error in a response project.

ESLint - The component should be written as a pure function (response preferred / stateless function)

It points to the first line of the component.

export class myComponent extends React.Component {
render() {
    return (

      //stuff here

    );
  }
}

How to get rid of this error?

+25
source share
8 answers

Two options

Temporarily disable the warning

(Not verified, and there are several ways to do this.)

// eslint-disable-next-line react/prefer-stateless-function
export class myComponent extends React.Component {
  ...
}

Use a clean, stateless component

The return value is what will be displayed (for example, you basically write a rendercomponent method based on a class:

export const myComponent = () => {
  return (
    // JSX here
  )
}

( -ES6, .)

,

export MyComponent = () =>
  <div>
    // Stuff here
  </div>

. , React, .

ESLint JSX, .

, :

const MyComponent = (props) =>
  <div>
    <Something someProp={props.foo} />
  </div>

export MyComponent

:

const MyComponent = ({ foo }) =>
  <div>
    <Something someProp={foo} />
  </div>

, . ESLint PropTypes ; , static propTypes , ( ).

+43

:

export myComponent = () => { //stuff here };

React: ( React) .

, state , componentDidMount, componentDidUpdate ..

, , , .

, , . . , this.props - .

+5

props, ( , ) - PureComponent eslint [source]:

"react/prefer-stateless-function": [2, { "ignorePureComponents": true }],

( props)

class Foo extends React.PureComponent {
  render() {
    return <div>{this.props.foo}</div>;
  }
}

React SFC, . , , SFCs PureComponents. , , .

+3

() :

exports class myComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <div>Hello</div>
    );
  }
}
+2

, , jsx-, constructor(props), , class .

.

export const myComponent = () => (
   // jsx goes here  
);
+1

, . , lint .

+1
const myComponent = () => {
return (
  //stuff here

  );
};

export default myComponent;

app.js , ,

import myComponent from './myComponent.js'

<myComponent />

.

0
export class myComponent extends PureComponent {
  ...
}
0

Source: https://habr.com/ru/post/1016506/


All Articles