简体   繁体   中英

Must use destructuring props assignment

I'm using Eslint in my React Native project, and in this code:

export default class AuthLoadingScreen extends React.Component {
  constructor() {
    super();
    this.bootstrapAsync();
  }

  bootstrapAsync = async () => {
    const userToken = await AsyncStorage.getItem('userToken');
    this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };

  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

Eslint given a warning: "Must use destructuring props assignment". I've tried to change assignment to

const navigation = this.props;
navigation.navigate(userToken ? 'App' : 'Auth');

But it gives an error: "undefined is not an object"

EDIT: changed the constructor to:

constructor(props) {
    super(props);
    this.bootstrapAsync(props);
  }

now code runs without errors

You should do it like this:

const { navigation } = this.props;
navigation.navigate(userToken ? 'App' : 'Auth');

Or if you want to go one lever deeper:

const { navigation: { navigate } } = this.props;
navigate(userToken ? 'App' : 'Auth');

But in that case the navigation object should be defined. Although it is possible to give a default value for destructuring objects.

Eg

const { navigation: { navigate } = {} } = this.props;

Now navigation will be an empty object if it's undefined.

If you only need the navigate function, then as Milore said, the best way of achieving what you'd like is:

const {navigate} = this.props.navigation

However, if you need to destructure other properties of navigation, you can use:

const {navigation} = this.props

Or destructure as Hespen recommended.

More on destructuring: MDN Documentation JS Info

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