必须使用解构道具赋值

Sgt*_*nut 7 javascript eslint react-native

我在 React Native 项目中使用 Eslint,在这段代码中:

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Eslint 给出警告:“必须使用解构道具赋值”。我试图将分配更改为

const navigation = this.props;
navigation.navigate(userToken ? 'App' : 'Auth');
Run Code Online (Sandbox Code Playgroud)

但它给出了一个错误:“未定义不是一个对象”

编辑: 将构造函数更改为:

constructor(props) {
    super(props);
    this.bootstrapAsync(props);
  }
Run Code Online (Sandbox Code Playgroud)

现在代码运行没有错误

Hes*_*pen 13

你应该这样做:

const { navigation } = this.props;
navigation.navigate(userToken ? 'App' : 'Auth');
Run Code Online (Sandbox Code Playgroud)

或者,如果您想更深入一层:

const { navigation: { navigate } } = this.props;
navigate(userToken ? 'App' : 'Auth');
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,应该定义导航对象。尽管可以为解构对象提供默认值。

例如

const { navigation: { navigate } = {} } = this.props;
Run Code Online (Sandbox Code Playgroud)

现在,如果导航未定义,它将是一个空对象。