必须使用破坏性道具分配 [英] Must use destructuring props assignment
本文介绍了必须使用破坏性道具分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的React Native项目中使用Eslint,并且在此代码中:
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发出警告:必须使用破坏性道具分配".我尝试将分配更改为
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"
将构造函数更改为:
constructor(props) {
super(props);
this.bootstrapAsync(props);
}
现在代码运行没有错误
推荐答案
您应该这样做:
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.
例如
const { navigation: { navigate } = {} } = this.props;
如果未定义,现在导航将是一个空对象.
Now navigation will be an empty object if it's undefined.
这篇关于必须使用破坏性道具分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文