预计 'this' 将被 class 方法使用

Expected 'this' to be used by class method

在我的 class 中,eslint 抱怨“预计 'this' 将被 class 方法使用 'getUrlParams'

这是我的 class:

class PostSearch extends React.Component {
  constructor(props) {
    super(props);
    this.getSearchResults();
  }

  getUrlParams(queryString) {
    const hashes = queryString.slice(queryString.indexOf('?') + 1).split('&');
    const params = {};

    hashes.forEach((hash) => {
      const [key, val] = hash.split('=');
      params[key] = decodeURIComponent(val);
    });

    return params;
  }

  getSearchResults() {
    const { terms, category } = this.getUrlParams(this.props.location.search);
    this.props.dispatch(Actions.fetchPostsSearchResults(terms, category));
  }

  render() {
    return (
      <div>
        <HorizontalLine />
        <div className="container">
          <Col md={9} xs={12}>
            <h1 className="aboutHeader">Test</h1>
          </Col>
          <Col md={3} xs={12}>
            <SideBar />
          </Col>
        </div>
      </div>
    );
  }
}

解决这个问题或重构这个组件的最佳方法是什么?

这是一个 ESlint 规则,参见 class-methods-use-this

您可以提取方法 getUrlParams 并将其放入 helper,或者使其成为 static.

你还可以做的是将 this.props.location.search 移动到方法内部,因此调用不带参数的 this.getUrlParams() 方法,因为你似乎只使用它一次。

因此,这可能看起来像:

getUrlParams() {
    const queryString = this.props.location.search;
    ...
    return params;
  }

最后一个选项是禁用此 ESlint 规则。

另一个用例可能是。

假设您有一个名为 handlePasswordKeyUp 的方法。函数体可以这样看

handlePasswordKeyUp() {
  console.log('yes')
}

以上代码将触发该错误。所以至少在 body 函数中使用 this

handlePasswordKeyUp(){
   this.setState({someState: someValue})
}

您应该将函数绑定到 this,因为 ESLint 错误显示 "Expected 'this' to be used by class method 'getUrlParams'

getUrlParams = (queryString) => { .... }

因为你在渲染期间没有使用 getUrlParams(比如 onClick())所以上面的技术很好,我们可以称之为 "usage of arrow function in class property".

还有其他绑定方式:

  • 构造函数中的绑定 this.getUrlParams=this.getUrlParams.bind(this)
  • 渲染中的箭头函数,例如onClick={()=>this.getUrlParams()}假设函数没有参数。
  • React.createClass 对 ES6 没有意义:)

对这条规则的一个可能的破解可能是。

getMoviesByID(){
  //Add a reference to this in your function.
  this.funcName = 'getMoviesByID';
}
getUrlParams = queryString => { ... }

我的解决方案是在 class 之外使用此函数并将此函数绑定到 class。

function getUrlParams(queryString) {
 const hashes = queryString.slice(queryString.indexOf('?') + 1).split('&');
 const params = {};
 hashes.forEach((hash) => {
  const [key, val] = hash.split('=');
  params[key] = decodeURIComponent(val);
 });
 return params;
}
class PostSearch extends React.Component {
  constructor(props) {
    super(props);
    this.getSearchResults();
    this.getUrlParams = getUrlParams.bind(this); // add this
  }

  getSearchResults() {
   const { terms, category } = this.getUrlParams(this.props.location.search);
   this.props.dispatch(Actions.fetchPostsSearchResults(terms, category));
  }
  render() {
   return (  "bla bla"  );
  }
}