itsource

클래스 메서드에서 'this'가 사용되어야 합니다.

mycopycode 2023. 3. 28. 21:47
반응형

클래스 메서드에서 'this'가 사용되어야 합니다.

제 수업에서 eslint가 "클래스 메서드 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>
    );
  }
}

이 문제를 해결하거나 이 컴포넌트를 리팩터링하는 최선의 방법은 무엇입니까?

이 함수는 에 바인드해야 합니다.thisESLint 오류에서 알 수 있듯이"Expected 'this' to be used by class method 'getUrlParams'

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

사용하고 있지 않기 때문에getUrlParams렌더링 중에(와 같은)onClick()따라서 위의 기법은 "클래스 속성의 화살표 함수"라고 할 수 있습니다.

다른 바인딩 방법도 있습니다.

  • 컨스트럭터에서의 바인딩this.getUrlParams=this.getUrlParams.bind(this)
  • 예를 들어, 렌더링의 화살표 기능.onClick={()=>this.getUrlParams()}해당 함수에 매개 변수가 없다고 가정합니다.
  • 그리고.React.createClassES6에서는 의미가 없습니다.

이것은 ESlint 규칙입니다.class-methods-use-this를 참조하십시오.

당신은 그 방법을 추출할 수 있다.getUrlParams도우미에게 넣거나 만들거나static.

또 할 수 있는 것은, 이 머신을this.props.location.search메서드 내부, 즉 콜링크를 호출합니다.this.getUrlParams()파라미터가 없는 메서드입니다.사용하는 것은 1회뿐인 것 같습니다.

그 때문에, 다음과 같이 됩니다.

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

마지막 옵션은 이 ESlint 규칙을 비활성화하는 것입니다.

getUrlParams = queryString => { ... }

저의 해결책은 이 기능을 교실 밖에서 사용하고 이 기능을 클래스에 바인드하는 것입니다.

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

또 다른 활용 사례는 다음과 같습니다.

handle Password Key Up이라고 하는 메서드가 있다고 합니다.함수의 본체는 이렇게 볼 수 있다.

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

위의 코드가 해당 오류를 트리거합니다.그래서 적어도 신체 기능 안에 이걸 쓰세요.

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

린터의 현재 eslint 문서에는 다음과 같이 기재되어 있습니다.

이 규칙은 사용하지 않는 클래스 메서드에 플래그를 지정하는 것을 목적으로 합니다.this.

그리고:

클래스 메서드가 이를 사용하지 않으면 정적 함수로 만들 수 있습니다.

고객의 코드에 그 예를 적용하면, 다음과 같이 됩니다.

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

  static 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 } = PostSearch.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>
    );
  }
}

주의:static함수를 호출하기 전에 함수 및 클래스 이름에 대한 수정자(예:this).

이 규칙에 대한 해킹 가능성이 있습니다.

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

언급URL : https://stackoverflow.com/questions/44249478/expected-this-to-be-used-by-class-method

반응형