React componet应该写成纯函数

时间:2017-04-06 05:30:25

标签: javascript reactjs ecmascript-6

这是我的ReactJs组件代码:

import React from 'react';

     class App extends React.Component {

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

    export default App;

Linting向我显示以下错误:

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

如何将其作为纯函数编写以避免此错误?

4 个答案:

答案 0 :(得分:5)

像这样:

import React from 'react';

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

export default App;

不需要保持状态的组件被称为&#34;无状态&#34;,并且通常被认为是最佳实践,除非您需要保持状态。

答案 1 :(得分:2)

一个简单的函数就足够了,你不需要一个完整的类(它应该只用于有状态组件)。您可以将代码缩减为

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 :(得分:1)

像这样写:

import React from 'react';

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

export default App;

原因是:您没有使用状态或任何生命周期方法,因此您可以将其设置为Pure Function。它基本上被称为Stateless Functional Component

查看doc了解详情。

答案 3 :(得分:0)

DECLARE @X XML ='<StartDate>2015-12-24T00:00:00</StartDate>
<EndDate>2015-12-29T15:39:20</EndDate>'


SELECT   @X.value('/StartDate[1]','DATETIME') AS START_DTE
        ,@X.value('/EndDate[1]','DATETIME') AS END_DTE

+-------------------------+-------------------------+
|        START_DTE        |         END_DTE         |
+-------------------------+-------------------------+
| 2015-12-24 00:00:00.000 | 2015-12-29 15:39:20.000 |
+-------------------------+-------------------------+