ESLint - Component should be written as a pure fun

2020-05-20 07:37发布

ESLint is giving me this error on a react project.

ESLint - Component should be written as a pure function (react prefer/stateless function)

It points to the first line of the component.

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

      //stuff here

    );
  }
}

How do I get rid of this error?

8条回答
相关推荐>>
2楼-- · 2020-05-20 08:07

Add constructor() like:

exports class myComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <div>Hello</div>
    );
  }
}
查看更多
小情绪 Triste *
3楼-- · 2020-05-20 08:08

If you rely on props, then there is a better (somewhat arguable, as of this writing) way to fix this error without writing out Stateless functions - by writing a PureComponent and using this eslint rule [source]:

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

With above rule, the following snippet is valid (since it depends on props)

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

React team plans to build optimizations around SFC but they are not there yet. So until that happens, SFCs will not offer any benefits over PureComponents. In fact, they will be slightly worse as they will not prevent wasteful renders.

查看更多
登录 后发表回答