React组件应该编写为纯函数

3

这里是我的ReactJs组件代码:

import React from 'react';

     class App extends React.Component {

        render() {
            return (
                <div className="wrapper">
                    <h1>Welcome to App!!!!</h1>
                </div>
                );
        }
     }

    export default App;

我看到 Lint 工具报了以下错误:

 error  Component should be written as a pure function  react/prefer-stateless-function

如何编写纯函数以避免此错误?
4个回答

6
就像这样:
import React from 'react';

const App = () => {
   return (
     <div className="wrapper">
          <h1>Welcome to App!!!!</h1>
     </div>
   );
}

export default App;

不需要保留状态的组件被称为“无状态”,通常被认为是最佳实践,除非您需要保留状态。


这导致了另一个错误:Unexpected block statement surrounding arrow body arrow-body-style - Mendes
2
你应该使用这个语法:https://gist.github.com/anonymous/2e812549e391f9f2bec85f678e397567 - roadev

3
一个简单的函数就足够了,你不需要整个类(这应该只用于有状态的组件)。你可以将代码简化为:
import React from 'react';

export default const App = () => (
  <div className="wrapper">
    <h1>Welcome to App!!!!</h1>
  </div>
);

或者

import React from 'react';

export default function App() {
  return (
    <div className="wrapper">
      <h1>Welcome to App!!!!</h1>
    </div>
  );
}

2

写成这样:

import React from 'react';

var App = () => {
    return (
        <div className="wrapper">
            <h1>Welcome to App!!!!</h1>
        </div>
    );
}

export default App;

原因是:您没有在其中使用任何状态或生命周期方法,因此可以将其作为纯函数。它基本上被称为无状态功能组件(Stateless Functional Component)

查看文档获取更多详细信息。


1
import React from 'react';

 const App = (props) => (
   <div className="wrapper">
     <h1>Welcome to App!!!!</h1>
   </div>
 );

export default App;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接