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.
E.g.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With