简体   繁体   English

ESLint - 组件应编写为纯函数(反应优先/无状态函数)

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

ESLint is giving me this error on a react project. ESLint 在反应项目中给了我这个错误。

ESLint - Component should be written as a pure function (react prefer/stateless function) ESLint - 组件应编写为纯函数(反应优先/无状态函数)

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?我如何摆脱这个错误?

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 (eg, you're basically writing class-based component's render method:返回值是将要呈现的内容(例如,您基本上是在编写基于类的组件的render方法:

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

(Or use non-ES6 notation if that's your thing.) (或者,如果您愿意,请使用非 ES6 符号。)

For components like this with no other supporting logic I prefer the implicit return, eg,对于像这样没有其他支持逻辑的组件,我更喜欢隐式返回,例如,

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.不过,我会说你应该遵循 React 命名约定,并让所有组件都以大写字母开头。

ESLint may complain about missing parens around a multi-line JSX expressions, so disable that rule or use parens. ESLint 可能会抱怨多行 JSX 表达式周围缺少括号,因此禁用该规则或使用括号。

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;除非您声明它们,否则您将收到有关缺少PropTypes的 ESLint 警告; 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).因为它不是一个类,所以你不能简单地在类中使用static propTypes ,它们必须附加到函数上(无论如何很多人都喜欢)。

Add constructor() like:添加构造函数(),如:

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

Write your component as a stateless function:将您的组件编写为无状态函数:

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

There are actually two styles of defining components in React: Functional components (which are just functions from props to a React component) and class components. React 中实际上有两种定义组件的风格:函数式组件(只是从 props 到 React 组件的函数)和类组件。

The main difference between them is that class components can have state and lifecycle methods such as componentDidMount , componentDidUpdate , etc.它们之间的主要区别在于类组件可以具有state和生命周期方法,例如componentDidMountcomponentDidUpdate等。

Whenever you don't need state of lifecycle methods, you should write your component as a stateless function, as stateless components are in general easier to reason about.当您不需要生命周期方法的状态时,您应该将组件编写为无状态函数,因为无状态组件通常更容易推理。

To write a functional component, you write a function that takes a single argument.要编写函数式组件,您需要编写一个接受单个参数的函数。 This argument will receive the component's props.此参数将接收组件的道具。 Consequently, you don't use this.props to access the component's props - you just use the function's argument.因此,您不使用this.props来访问组件的 props - 您只使用函数的参数。

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] :如果您依赖props ,那么有一种更好的(在撰写本文时有些争议)方法来修复此错误而无需编写无状态函数 - 通过编写PureComponent并使用此 eslint 规则[source]

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

With above rule, the following snippet is valid (since it depends on props )根据上述规则,以下代码段是有效的(因为它取决于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. React 团队计划围绕 SFC 构建优化,但目前还没有。 So until that happens, SFCs will not offer any benefits over PureComponents .因此,在此之前, SFCs不会比PureComponents提供任何好处。 In fact, they will be slightly worse as they will not prevent wasteful renders.事实上,它们会稍微糟糕一些,因为它们不会防止浪费渲染。

You will get this error only when your class does not have any life cycle method or constructor.只有当您的类没有任何生命周期方法或构造函数时,您才会收到此错误。 To solve this either you have to disable the lint property or make it as a pure function or create constructor for the class.要解决此问题,您必须禁用 lint 属性或将其设为纯函数或为类创建构造函数。

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

  );
};

export default myComponent;

And in app.js file just import this component as we do for class like在 app.js 文件中只需像我们在类中所做的那样导入这个组件

import myComponent from './myComponent.js'

and call as并称为

<myComponent />

It will work for sure.它肯定会起作用。

export class myComponent extends PureComponent {
  ...
}

If all you're doing is rendering a jsx template, and not declaring state with constructor(props) , then you should write your component as a pure function of props, and not use the class keyword to define it.如果您所做的只是渲染一个 jsx 模板,而不是使用constructor(props)声明状态,那么您应该将组件编写为 props 的纯函数,而不是使用class关键字来定义它。

ex.前任。

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

you need to add constructor(props)你需要添加构造函数(道具)

export class myComponent extends React.Component {
    constructor(props) {
            super(props);
            this.state = {};
        }
    render() {
        return (
    
          //stuff here
    
        );
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM