Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

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

ESLint is giving me this error on a react project.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two choices.

Temporarily disable warning

(Untested; and there are multiple ways to do this.)

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

Use a pure stateless component

The return value is what will be rendered (e.g., you're basically writing class-based component's render method:

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

(Or use non-ES6 notation if that's your thing.)

For components like this with no other supporting logic I prefer the implicit return, e.g.,

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

This is a matter of preference. I would say that you should follow React naming conventions, though, and keep all components starting with an upper-case letter.

ESLint may complain about missing parens around a multi-line JSX expressions, so disable that rule or use parens.

If you need props, they're passed in as the argument to the function:

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

export MyComponent

And you can destructure in the parameter as usual for convenience:

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

This can make the implicit return a little easier if you were using local vars. You'll get an ESLint warning about missing PropTypes unless you declare them; since it's not a class you cannot simply use static propTypes in the class, they must be attached to the function (which many people prefer anyway).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...