简体   繁体   中英

How to avoid TypeError: Cannot read property 'picture' of undefined in React Native?

this.props.navigation.state.params.picture is throwing TypeError: Cannot read property 'picture' of undefined

I want to check if it is readable or not.

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

if i write let varPicPath; instead of let varPicPath = this.props.navigation.state.params.picture; then console.warn prints hi undefined

Hope you're getting the point.

Try somethinhg like this :

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

Hope it helps.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM