статическая оценка реквизита, приводящая к исключению - PullRequest
0 голосов
/ 30 сентября 2019

Я звоню ниже SomeComponent как следует. SomeComponent.render происходит нормально. Но когда я вызываю show метод, я получаю undefined is not an object 'arr[index].something'

<SomeComponent arr={arr} />

export default class SomeComponent extends Component {

  static propTypes = {
    arr: PropTypes.arrayOf(PropTypes.any).isRequired,   
  };

  state = {
    x: 1, 
    x: 2,   
  };

  show(index) {
    const {arr} = this.props;
    if(arr[index].something){ // Here i get the issue. Seems likes arr is undefined.
    }   
  }

  render() {
    const {arr} = this.props;
    return(
      <Viewer images={arr} show={currentIndex => this.show(currentIndex)} />
    )   
  } 
}

1 Ответ

1 голос
/ 30 сентября 2019
show = (index) =>{
  const {arr} = this.props;
  if(arr[index].something){ // Here i get the issue. Seems likes arr is undefined.
  }   
 }

измените эту функцию следующим образом

   this.show = this.show.bind(this)

или добавьте эту строку в конструктор, экземпляр компонента (this.props) не может быть доступен в функции без функции привязки

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...