10

我正在使用 airbnb eslint 设置,它具有强制将无状态反应组件重写为纯函数的规则。下面的组件触发了这个规则,这意味着下面的组件最好写成纯函数:

import React from 'react';
import { observer } from 'mobx-react';
import cssmodules from 'react-css-modules';

import styles from './index.css';
import Select from '../Select/';
import List from '../List/';

@cssmodules(styles)
@observer
export default class Analysis extends React.Component {
  render() {
    return (
      <div styleName="wrapper">
        <div styleName="column">
          <Select store={this.props.store} />
        </div>
        <div styleName="column">
          <List store={this.props.store} />
        </div>
      </div>
    );
  }
}

Analysis.propTypes = {
  store: React.PropTypes.object.isRequired,
};

但是,当我将它重写为纯函数(见下文)时,我收到以下错误Leading decorators must be attached to a class declaration

import React from 'react';
import { observer } from 'mobx-react';
import cssmodules from 'react-css-modules';

import styles from './index.css';
import Select from '../Select/';
import List from '../List/';

@cssmodules(styles)
@observer
function Analysis(props) {
  return (
    <div styleName="wrapper">
      <div styleName="column">
        <Select store={props.store} />
      </div>
      <div styleName="column">
        <List store={props.store} />
      </div>
    </div>
  );
}

Analysis.propTypes = {
  store: React.PropTypes.object.isRequired,
};

那么我可以把它写成一个纯组件并仍然附加装饰器吗?或者这是airbnb linting规则中的一个错误,不可能同时满足这两个规则?

4

1 回答 1

16

好的,问题出在 es7 风格的装饰器上。对它们进行脱糖可以解决问题:

import React from 'react';
import { observer } from 'mobx-react';
import cssmodules from 'react-css-modules';

import styles from './index.css';
import Select from '../Select/';
import List from '../List/';

function Analysis(props) {
  return (
    <div styleName="wrapper">
      <div styleName="column">
        <Select store={props.store} />
      </div>
      <div styleName="column">
        <List store={props.store} />
      </div>
    </div>
  );
}

Analysis.propTypes = {
  store: React.PropTypes.object.isRequired,
};

export default cssmodules(observer(Analysis), styles);

它不漂亮,但它确实有效并且不会触发任何错误。

于 2016-09-14T10:49:18.977 回答