Undefined 不是对象(正在计算 'this.state.username')

Undefined is not an object (evaluating 'this.state.username')

我是React Native的菜鸟,刚开始学习。 我想使用 React Native 构建 Android 应用程序。

现在,我有一个基本的登录表单,它将向服务器发送获取请求并显示用户是否已获得授权。

但是当我尝试提醒输入字段的值时它抛出错误 "Undefined is not an object"

我指的是官方文档here,这段代码有效。 我也尝试过基本的反应形式 here 。 我正在使用 UI kitten text input 作为输入,我也使用了原生的 React TextInput,它给出了同样的错误。

我当前的代码是:

import React from 'react';
import { Alert, StyleSheet, Text, TextInput, View } from 'react-native';
import {RkButton, RkText, RkTextInput, RkCard} from 'react-native-ui-kitten';
import Icon from 'react-native-vector-icons/Ionicons';

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

    this.state = {
      username: '',
      password: ''
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    const target = event.target;

    this.setState({
      username: target.username,
      password: target.password
    });
  }


  login()
  {
    Alert.alert(this.state.username) //getting error here

    let data = {
      method: 'POST',
      credentials: 'same-origin',
      mode: 'same-origin',
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password
      }),
      headers: {
        'Accept':       'application/json',
        'Content-Type': 'application/json',
      }
    }
    fetch('http://demourl.com/login',data)
    .then((response) => response.json())
    .then((responseJson) => {
      if (responseJson.success == 'true') {
        Alert.alert('Login Successfull!')
      }
      else {
        Alert.alert('Login Failed')
      }
    })
    .catch((error) => {
      console.error(error);
    });
    ;
  }

  render() {
    return (
      <View style={styles.container}>
        <RkCard style={{padding: 20}}>
          <View style={{alignItems: 'center',padding: 10}}>
            <RkText rkType='warning large' style={{fontSize: 40}}>Log In</RkText>
          </View>
          <View style={{alignItems: 'center',padding: 10}}>
            <RkTextInput placeholder='Username' value={this.state.username} onChange={this.handleChange} />
            <RkTextInput placeholder='Password' value={this.state.password} onChange={this.handleChange}/>
          </View>
          <View style={{alignItems: 'center',padding: 10}}>
            <RkButton rkType='success small' title="Press Me"
              onPress={this.login}
            >Log In!</RkButton>
          </View>
        </RkCard>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    marginTop: 65,
    backgroundColor: '#fff',
    justifyContent: 'center',
    padding: 10
  },
});

请告诉我我哪里不明白工作原理。或者我的代码哪里有问题。 提前致谢。

像绑定 handleChange 那样绑定 login 函数,或者像

一样使用 arrow 函数
login = () => {
  ...
}

看看箭头函数文档here

希望这会有所帮助!