Reactjs ReferenceError:在React Native 0.60.4中找不到变量:状态

Reactjs ReferenceError:在React Native 0.60.4中找不到变量:状态,reactjs,react-native,react-native-android,react-native-router-flux,react-state,Reactjs,React Native,React Native Android,React Native Router Flux,React State,我正在使用React native 0.60.4和React native router flux 4.0.6。 我有一个可以正常工作的登录组件,但是当我在用户更改密码后将用户重定向到登录屏幕时,上面的错误弹出,应用程序崩溃 我尝试在ComponentDidMount中打印状态变量-它会被打印出来。将打印构造函数中初始化状态变量的所有日志。 发布此消息后,错误弹出,应用程序崩溃 部分错误消息: [08:42:09]我有反应▶︎ 登录组件挂载 [08:42:09]E |反应性JS▶︎ Refere

我正在使用React native 0.60.4和React native router flux 4.0.6。 我有一个可以正常工作的登录组件,但是当我在用户更改密码后将用户重定向到登录屏幕时,上面的错误弹出,应用程序崩溃

我尝试在ComponentDidMount中打印状态变量-它会被打印出来。将打印构造函数中初始化状态变量的所有日志。 发布此消息后,错误弹出,应用程序崩溃

部分错误消息:

[08:42:09]我有反应▶︎ 登录组件挂载

[08:42:09]E |反应性JS▶︎ ReferenceError:找不到变量:state

我相信代码中没有问题,因为无论何时加载应用程序,它都可以正常工作

代码:


在我从react native 0.56.0升级到0.60.4之前,我的代码运行良好,并且我还将react native router flux从^4.0.0-beta.28升级到^4.0.6。不太确定这条信息是否有用。

嗯,您必须直接使用state,而不是导致此问题的this.state。在构造函数中初始化而没有数据类型的任何内容都应该被认为是使用此运算符初始化的,以便使用this.abc在整个类中访问它

这是因为您的unsubscribe函数是在类外定义的,它在登录函数中被调用,而且当您在登录中调用unsubscribe时,它应该是NetInfo.removeEventListener

NetInfo.addEventListenerchange=>{this.handleConnectionChange}

应该改成

this.unsubscribe=NetInfo.addEventListener'connectionChange',this.handleConnectivityChange

所以最后应该是这样的:

let deviceWidth = Dimensions.get('window').width;
let elementWidth = 0.8 * deviceWidth;
let screenHeigth = Dimensions.get('window').height;


class LoginScreen extends React.Component {
  constructor(props) {
    console.log("Props done");
    super(props);
    console.log("State issue");
    this.state = {
      appState: AppState.currentState,
      hidePwd: true,
      pntoken: '',
      username: '',
      passwd: '',
      text: '',
      checkinternet: false,
      nointernet: false,
      isLoading: false,
      visibleHeight: Dimensions.get('window').height,

      logo_height: 100,
      logo_width: 100,
      pwd_backup: ''

    };
    console.log("State initialized");
    this.handleConnectivityChange = this.handleConnectivityChange.bind(this);
    this.unsubscribe = NetInfo.addEventListener('connectionChange', this.handleConnectivityChange);
    this._handleAppStateChange = this._handleAppStateChange.bind(this);
    this.requestLocationPermission = this.requestLocationPermission.bind(this);

    if (Platform.OS === 'android') {
      UIManager.setLayoutAnimationEnabledExperimental(true);
    }
  }

  componentDidMount() {
    console.log(this.state);
    console.log("login componentDidMount");
    this.getfcmtooken();
    NetInfo.fetch().then((connectionInfo) => {
      if (connectionInfo.type != 'none') {
        console.log("NETINFO");
        this.setState({ checkinternet: false, nointernet: false });
        this.requestCameraPermission();
      }
      else {
        this.setState({ checkinternet: false, nointernet: true });
      }
    })
      .catch((response) => {
        console.log(response);
      });

    AppState.addEventListener('change', this._handleAppStateChange);

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow.bind(this))
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide.bind(this))
  }

  login() {
    if (this.state.username != '') {
      let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if (reg.test(this.state.username) === true) {
        if (this.state.passwd != '') {
          return fetch(this.props.apiurl + '/mobilelogin', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              email: this.state.username,
              password: this.state.passwd,
              pntoken: this.state.pntoken,
            }),
          })
            .then((response) => response.json())
            .then((responseJson) => {
              if (responseJson.statusCode == 200) {
                this.setState({
                  isLoading: false,
                  text: responseJson.result.authenticateUser.userRole,
                  dataSource: responseJson
                }, function () {
                  try {
                    console.log('TOKEN');
                    console.log(JSON.stringify(responseJson.result.authenticateUser.token));
                    AsyncStorage.setItem('token', JSON.stringify(responseJson.result.authenticateUser.token));
                    AsyncStorage.setItem('email', JSON.stringify(responseJson.result.authenticateUser.email));
                    AsyncStorage.setItem('userRole', JSON.stringify(responseJson.result.authenticateUser.userRole));
                    AsyncStorage.setItem('org_id', JSON.stringify(responseJson.result.authenticateUser.orgId));
                    AsyncStorage.setItem('user_id', JSON.stringify(responseJson.result.authenticateUser.userId));
                    this.getfcmtooken();
                    AppState.removeEventListener('change', this._handleAppStateChange);
                    // this.unsubscribe();
                    NetInfo.removeEventListener('connectionChange', this.handleConnectivityChange );
                    Actions.landing();
                  } catch (error) {
                    console.log(error)
                  }
                });
              }
              else {
                ToastAndroid.show(responseJson.authenticateUser.statusMessage, ToastAndroid.LONG);
              }
            })
            .catch((error) => {
              console.log('error');
              console.log(error);
            });
        }
        else {
          ToastAndroid.show('Password is mandatory', ToastAndroid.LONG);
        }
      }
      else {
        ToastAndroid.show('Email is not in correct form', ToastAndroid.LONG);
      }
    }
    else {
      ToastAndroid.show('Email is mandatory', ToastAndroid.LONG);
    }
  }
}

我只粘贴了更改后的函数。

它可以与此.state一起使用,你能分享一下你的代码吗?用代码编辑了这个问题这是因为你有一个非注册函数class@warl0ck这应该会给我一个错误,当我第一次加载它…但它的工作很好…我仍在尝试与你的建议。希望它能起作用…我已经提到了这些变化,看看能不能起作用,另外,我想当你调用unsubscribe时,它不会删除订阅,因为你将不得不删除VentListener并进行必要的更改。我也认为这是一个问题,并对此进行了检查……但找不到任何此类实例……我仅使用this.state访问了状态。。。。我想知道这是否与react本机路由器流量或导航代码有关……还是同一个问题吗?即使没有打过电话。退订?。你能从chrome调试器共享崩溃日志吗。而不是从adb日志?并在使用箭头函数时从_handleAppStateChange函数中删除绑定。刚才注意到,在使用箭头函数时从_handleAppStateChange函数中删除绑定会自动为您绑定。在进行建议的更改后重试。。。还是一样的问题
let deviceWidth = Dimensions.get('window').width;
let elementWidth = 0.8 * deviceWidth;
let screenHeigth = Dimensions.get('window').height;


class LoginScreen extends React.Component {
  constructor(props) {
    console.log("Props done");
    super(props);
    console.log("State issue");
    this.state = {
      appState: AppState.currentState,
      hidePwd: true,
      pntoken: '',
      username: '',
      passwd: '',
      text: '',
      checkinternet: false,
      nointernet: false,
      isLoading: false,
      visibleHeight: Dimensions.get('window').height,

      logo_height: 100,
      logo_width: 100,
      pwd_backup: ''

    };
    console.log("State initialized");
    this.handleConnectivityChange = this.handleConnectivityChange.bind(this);
    this.unsubscribe = NetInfo.addEventListener('connectionChange', this.handleConnectivityChange);
    this._handleAppStateChange = this._handleAppStateChange.bind(this);
    this.requestLocationPermission = this.requestLocationPermission.bind(this);

    if (Platform.OS === 'android') {
      UIManager.setLayoutAnimationEnabledExperimental(true);
    }
  }

  componentDidMount() {
    console.log(this.state);
    console.log("login componentDidMount");
    this.getfcmtooken();
    NetInfo.fetch().then((connectionInfo) => {
      if (connectionInfo.type != 'none') {
        console.log("NETINFO");
        this.setState({ checkinternet: false, nointernet: false });
        this.requestCameraPermission();
      }
      else {
        this.setState({ checkinternet: false, nointernet: true });
      }
    })
      .catch((response) => {
        console.log(response);
      });

    AppState.addEventListener('change', this._handleAppStateChange);

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow.bind(this))
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide.bind(this))
  }

  login() {
    if (this.state.username != '') {
      let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if (reg.test(this.state.username) === true) {
        if (this.state.passwd != '') {
          return fetch(this.props.apiurl + '/mobilelogin', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              email: this.state.username,
              password: this.state.passwd,
              pntoken: this.state.pntoken,
            }),
          })
            .then((response) => response.json())
            .then((responseJson) => {
              if (responseJson.statusCode == 200) {
                this.setState({
                  isLoading: false,
                  text: responseJson.result.authenticateUser.userRole,
                  dataSource: responseJson
                }, function () {
                  try {
                    console.log('TOKEN');
                    console.log(JSON.stringify(responseJson.result.authenticateUser.token));
                    AsyncStorage.setItem('token', JSON.stringify(responseJson.result.authenticateUser.token));
                    AsyncStorage.setItem('email', JSON.stringify(responseJson.result.authenticateUser.email));
                    AsyncStorage.setItem('userRole', JSON.stringify(responseJson.result.authenticateUser.userRole));
                    AsyncStorage.setItem('org_id', JSON.stringify(responseJson.result.authenticateUser.orgId));
                    AsyncStorage.setItem('user_id', JSON.stringify(responseJson.result.authenticateUser.userId));
                    this.getfcmtooken();
                    AppState.removeEventListener('change', this._handleAppStateChange);
                    // this.unsubscribe();
                    NetInfo.removeEventListener('connectionChange', this.handleConnectivityChange );
                    Actions.landing();
                  } catch (error) {
                    console.log(error)
                  }
                });
              }
              else {
                ToastAndroid.show(responseJson.authenticateUser.statusMessage, ToastAndroid.LONG);
              }
            })
            .catch((error) => {
              console.log('error');
              console.log(error);
            });
        }
        else {
          ToastAndroid.show('Password is mandatory', ToastAndroid.LONG);
        }
      }
      else {
        ToastAndroid.show('Email is not in correct form', ToastAndroid.LONG);
      }
    }
    else {
      ToastAndroid.show('Email is mandatory', ToastAndroid.LONG);
    }
  }
}