【问题标题】:Must use destructuring props assignment [duplicate]必须使用解构道具分配[重复]
【发布时间】:2019-05-11 18:34:27
【问题描述】:

我在我的 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>
    );
  }
}

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

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

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

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

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

现在代码运行没有错误

【问题讨论】:

    标签: javascript react-native eslint


    【解决方案1】:

    你应该这样做:

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

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

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

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

    例如

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

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

    【讨论】:

    • 可以改用:const { navigate } = this.props.navigation;?
    • 是的,您可以解构每个对象。 this.propsthis.props.navigation 都是对象,因此您可以将该结构应用于它们。
    • 我终于弄清楚出了什么问题。我没有将props传递给构造函数,而是尝试调用this.bootstrapAsync();我添加了props,现在这部分代码看起来像constructor(props) { super(props); this.bootstrapAsync(props); }并且运行良好
    【解决方案2】:

    如果您只需要导航功能,那么正如 Milore 所说,实现您想要的最佳方式是:

    const {navigate} = this.props.navigation

    但是,如果您需要解构导航的其他属性,您可以使用:

    const {navigation} = this.props

    或者按照 Hespen 的建议进行解构。

    更多关于解构:MDN DocumentationJS Info

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 2019-04-20
      • 2021-11-17
      • 1970-01-01
      • 2021-03-23
      • 2019-11-27
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多