programing

React.js - 정의되지 않은 속성을 읽을 수 없습니다.

kingscode 2023. 3. 12. 12:19
반응형

React.js - 정의되지 않은 속성을 읽을 수 없습니다.

저는 아주 간단한 리액트 앱을 만들고 있어요.그러나 onChange 이벤트를 통해 부모(실제로 조부모) 컴포넌트의 메서드를 호출하려고 하면 계속 취득됩니다.Uncaught TypeError: Cannot read property 'props' of undefined.

다음은 이벤트를 트리거하는 구성 요소/폼입니다(따라서 바인딩된 상위 구성 요소에서 메서드를 호출합니다).네, 부모 컴포넌트에서 소품을 통해 전달하기 때문에 메서드에 .bound(이것)를 사용했습니다.

class MonthsTable extends Component {
  handleChangeOnMonth(e){ 
    this.props.setMonth(e.target.id, e.target.value); // here the method is not found, causing error.
  }
  render(){
    console.log(this.props.setMonth) // here the method is present alright
    return (<form>
      {this.props.months.map((e, i) =>
         <input
          type='number'
          id={i} 
          key={i} // yes I know, bad habit, but in this case it doesn't matter
          value={this.props.months[i]}
          onChange={this.handleChangeOnMonth} />)}
    </form>)
  }
}

대부분의 부모(대부) 컴포넌트의 소품으로서 메서드를 건네는 방법은 다음과 같습니다.

<Months setMonth={this.setMonth.bind(this)} />

부모(메서드 소유자와 메서드 호출자 사이에 있는 컴포넌트)에서 메서드를 소품으로 전달하는 방법은 다음과 같습니다.

<MonthsTable setMonth={this.props.setMonth} />

마지막으로 처음에 본 컴포넌트(MonthsTable)로 넘어갔습니다.관련성이 있든 없든 어떤 문장이 정상적으로 동작하는지에 따라 최종(대부분의 아이) 컴포넌트가 표시됩니다(어느 정도 관련성이 있을 수 있습니다만, 잘 모르겠습니다).

문제는...(handle Change On Month) 메서드의 내부에 (set Month) 메서드가 '보이지 않는' 이유는 무엇입니까?

여기서의 진짜 문제는this컨텍스트가 정의되어 있지 않습니다.handleChangeOnMonth기능.이는 javascript가 함수의 콘텍스트를 처리하는 방식 때문에 발생합니다.기본적으로 객체에서 직접 함수를 호출하지 않을 경우 함수를 호출할 때 정의된 콘텍스트가 없습니다.또한 함수를 입력 컴포넌트에 파라미터로 전달하고 있기 때문에 콘텍스트가 손실됩니다.

이를 수정하는 가장 간단한 방법은 함수를 바인딩하는 것입니다. 다음과 같이 함수를 컨스트럭터에서 바인딩할 것을 권장합니다.

class MonthsTable extends Component {
  constructor(props, context){
    super(props, context);
    this.handleChangeOnMonth = this.handleChangeOnMonth.bind(this);
  }
  handleChangeOnMonth(e){ 
    this.props.setMonth(e.target.id, e.target.value);
  }
  render(){
    return (<form>
      {this.props.months.map((e, i) =>
         <input
          type='number'
          id={i} 
          key={i} 
          value={this.props.months[i]}
          onChange={this.handleChangeOnMonth} />)}
    </form>)
  }
}

또는 데코레이터를 사용하는 경우core-decorators보다 우아한 방법으로 이것을 실현하기 위한 패키지:

import {autobind} from "core-decorators"

@autobind
class MonthsTable extends Component {     
  handleChangeOnMonth(e){ 
    this.props.setMonth(e.target.id, e.target.value);
  }
  render(){
    return (<form>
      {this.props.months.map((e, i) =>
         <input
          type='number'
          id={i} 
          key={i} 
          value={this.props.months[i]}
          onChange={this.handleChangeOnMonth} />)}
    </form>)
  }
}

onChange에 제공된 함수를 현재 컨텍스트에 바인딩해야 합니다.클래스 컨스트럭터에서 바인드할 수도 있고 onChange()에 직접 바인드할 수도 있습니다.이것은 좋은 프랙티스가 아닙니다.

class MonthsTable extends Component {
  constructor(props){
    super(props);
    this.handleChangeOnMonth = this.handleChangeOnMonth.bind(this);
  }
  handleChangeOnMonth(e){ 
    this.props.setMonth(e.target.id, e.target.value); // here the method is not found, causing error.
  }
  render(){
    console.log(this.props.setMonth) // here the method is present alright
    return (<form>
      {this.props.months.map((e, i) =>
         <input
          type='number'
          id={i} 
          key={i} // yes I know, bad habit, but in this case it doesn't matter
          value={this.props.months[i]}
          onChange={this.handleChangeOnMonth.bind(this)} />)}
    </form>)
  }
}

작성한 모든 함수를 묶지 않으려면ES6 화살표 기능을 사용할 수 있습니다.화살표 기능에는 자체 기능이 없기 때문에 이 기능이 작동합니다.this, 그래서 그들은 클래스의 것을 상속합니다.this. Lexical Scoping에 대한 자세한 내용은 여기를 참조하십시오.이 솔루션은 실제로 문서에 기재되어 있습니다.

handleChangeOnMonth = (e) => { 
  this.props.setMonth(e.target.id, e.target.value);
}

언급URL : https://stackoverflow.com/questions/39176248/react-js-cant-read-property-of-undefined

반응형