期望“this”被类方法使用

新手上路,请多包涵

在我的课堂上,eslint 抱怨“预期‘this’被类方法‘getUrlParams’使用

这是我的课:

 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>
    );
  }
}

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

原文由 Hinesh Patel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 681
2 个回答

您应该将函数绑定到 this 正如 ESLint 错误所说 "Expected 'this' to be used by class method 'getUrlParams'

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

因为你在渲染过程中没有使用 getUrlParams (比如 onClick() )所以上面的技术很好,我们可以称之为“在类属性中使用箭头函数”。

还有其他绑定方式:

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

原文由 Amir-Mousavi 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

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

因此,这可能看起来像:

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

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

原文由 Ioan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题