Как избежать TypeError: Не удается прочитать свойство 'picture' из undefined в React Native? - PullRequest
1 голос
/ 11 марта 2020

this.props.navigation.state.params.picture генерирует TypeError: Cannot read property 'picture' of undefined

Я хочу проверить, читаемо это или нет.

componentDidMount = async () => {
    try {
      let varPicPath = this.props.navigation.state.params.picture;
      if (typeof varPicPath === 'undefined') {
        console.warn('hi' + varPicPath);
      }
    } catch (error) {
      console.warn(error);
    }
  };

если я напишу let varPicPath; вместо let varPicPath = this.props.navigation.state.params.picture; тогда console.warn печатает hi undefined

Надеюсь, вы получите точку.

Ответы [ 2 ]

1 голос
/ 11 марта 2020

Попробуйте это:

componentDidMount = async () => {
    try {
      let varPicPath = this.props.navigation.state.params == null ? null: this.props.navigation.state.params.picture;
      if (typeof varPicPath == null) {
        console.warn('hi' + varPicPath);
      }
    } catch (error) {
      console.warn(error);
    }
  };
1 голос
/ 11 марта 2020

Попробуйте что-нибудь вроде этого:

      let picture = '';
        if(this.props.navigation.state.params) {
          picture = this.props.navigation.state.params.picture;
        }
        return picture;

Надеюсь, это поможет.

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