Must use destructuring props assignment [duplicate]

断了今生、忘了曾经 提交于 2021-02-08 19:44:08

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/53712796/must-use-destructuring-props-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!