构造函数内部的函数返回undefined

时间:2020-08-18 13:51:45

标签: javascript react-native

我正在努力编写自己认为可行的代码。

问题是在构造函数中定义的函数返回undefined,因此,当事件发生时尝试分配它们时,会出现以下错误:

Invalid type undefined for OnConnect

下面是一个简短的示例(问题末尾的完整代码)

export default class App extends Component {
  constructor(props) {
    super(props)

    // this is a function defined inside the constructor
    onConnect = () => {
      // some code
    };

    // but if I try to print it, it returns undefined
    console.log(this.onConnect)
  }
}

所以问题是此函数的定义错误。他们使用箭头功能,对我来说看起来很好,所以我不知道为什么它说它是未定义的。

完整代码:

import React, { Component } from 'react';
import init from 'react_native_mqtt';
import { AsyncStorage, StyleSheet, Text, View } from 'react-native';

init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  sync: {},
});

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
  },
});

export default class MqttLog extends Component {
  constructor(props) {
    super(props);

    const client = new Paho.MQTT.Client('iot.eclipse.org', 443, 'uname');
    client.onConnectionLost = this.onConnectionLost;
    client.onMessageArrived = this.onMessageArrived;
    client.connect({ onSuccess: this.onConnect, useSSL: true });

    this.state = {
      text: ['...'],
      client,
    };
  }

  pushText = entry => {
    const { text } = this.state;
    this.setState({ text: [...text, entry] });
  };

  onConnect = () => {
    const { client } = this.state;
    client.subscribe('WORLD');
    this.pushText('connected');
  };

  onConnectionLost = responseObject => {
    if (responseObject.errorCode !== 0) {
      this.pushText(`connection lost: ${responseObject.errorMessage}`);
    }
  };

  onMessageArrived = message => {
    this.pushText(`new message: ${message.payloadString}`);
  };

  render() {
    const { text } = this.state;

    return (
      <View style={styles.container}>
        {text.map(entry => <Text>{entry}</Text>)}
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:3)

如评论中所述: 您的第一个示例不同于秒,因为第一个示例是在构造函数内部创建onConnect函数,第二个示例是在类级别。

如果您首先希望它是正确的,则必须像这样创建它:

export default class App extends Component {
  constructor(props) {
    super(props)

    // this is a function defined inside the constructor
    this.onConnect = () => {
      // some code
    };

    // but if I try to print it, it returns undefined
    console.log(this.onConnect)
  }
}

后面的代码似乎正确。