简体   繁体   English

react-native:`this.state`在登录函数中未定义

[英]react-native: `this.state` is undefined in login function

I'm having trouble accessing this.state in functions inside my component. 我在组件内部的函数中访问this.state遇到麻烦。

Always I get "Undefined is not a object this.state.username , this.state.password " error 我总是收到“未定义不是对象this.state.usernamethis.state.password ”错误

SimpleForm.js SimpleForm.js

import Expo from 'expo';
import React from 'react';
import { StackNavigator, DrawerNavigator } from 'react-navigation';
import App from './App';
import RegisterForm from './register';
import { View, Text, TextInput, Image, TouchableOpacity, AsyncStorage, StyleSheet } from 'react-native';
import { YourRestApi } from './constants/api3';

class SimpleForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '', password: '', datas: '' };
    this.login = this.login.bind(this, this.state.username, this.state.password);
  }
  componentWillMount() {
    this.login();
  }

  registerscreen = () => {
    this.props.navigation.navigate('Register');
  }


   login() {
    YourRestApi(this.state.username, this.state.password)
      .then((response) => {
        console.log(response.success);
        this.setState({ loading: false, datas: response });
      });
    if (this.state.datas.success === true) {
      const info = this.state.datas.message;

      AsyncStorage.setItem('info', JSON.stringify(info));
      this.props.navigation.navigate('SecondScreen');
    } else {
      alert(this.state.datas.message);
    } 
  }

   render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <Image source={require('./assets/img/sd.png')} style={styles.backgroundImage}>
          <View style={styles.content}>
            <Text style={styles.logo}>Toto Prediction </Text>
            <View style={styles.inputContainer}>

              <TextInput
                underlineColorAndroid='transparent' style={styles.input}
                onChangeText={(username) => this.setState({ username })} 
                value={this.state.username} placeholder='username'
              /> 

              <TextInput
                secureTextEntry underlineColorAndroid='transparent' style={styles.input}
                onChangeText={(password) => this.setState({ password })} 
                value={this.state.password} placeholder='password'
              /> 
            </View>
            <TouchableOpacity onPress={this.login} style={styles.buttonContainer}>
              <Text style={styles.buttonText}>Login</Text>
            </TouchableOpacity>
            this._onPressGet.bind(this)
            <TouchableOpacity onPress={this.registerscreen} style={styles.buttonContainer}>
              <Text style={styles.buttonText}>Register</Text>
            </TouchableOpacity>
          </View>
        </Image>
      </View>

    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundImage: {
    flex: 1,
    alignSelf: 'stretch',
    width: null,
    justifyContent: 'center', 
  },
  content: {
    alignItems: 'center',
  },
  logo: {
    color: 'white',
    fontSize: 40,
    fontStyle: 'italic',
    fontWeight: 'bold',
    textShadowColor: '#252525',
    textShadowOffset: { width: 2, height: 2 },
    textShadowRadius: 15,
    marginBottom: 20,
  },
  inputContainer: {
    margin: 20,
    marginBottom: 0,
    padding: 20,
    paddingBottom: 10,
    alignSelf: 'stretch',
    borderWidth: 1,
    borderColor: '#fff',
    backgroundColor: 'rgba(255,255,255,0.2)',
  },
  input: {
    fontSize: 16,
    height: 40,
    padding: 10,
    marginBottom: 10,
    backgroundColor: 'rgba(255,255,255,1)',
  },
  buttonContainer: {
    margin: 20,
    padding: 20,
    backgroundColor: 'blue',
    borderWidth: 1,
    borderColor: '#fff',
    backgroundColor: 'rgba(255,255,255,0.6)',
  },
  buttonText: {
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});
const SimpleApp = DrawerNavigator({
  Onescreen: { screen: SimpleForm },
  SecondScreen: { screen: App },
  Register: { screen: RegisterForm },
});
Expo.registerRootComponent(SimpleApp);

Api3.js Api3.js

export function YourRestApi(username1, password1) {
  fetchlogin(username1, password1);
}
function fetchlogin(username1, password1) {
  const details = {
    username: username1,
    password: password1,
  };
  const formBody = Object.keys(details).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`).join('&');

  fetch('https://*********************', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: formBody,
  })
    .then((response) => response.json())
    .then((response) => {
      console.log('requestAppInstallation success ', response);
      return response;
    })
    .done();
}

I tried binding login to this.state but doesnt worked 我尝试将登录名绑定到this.state但没有用

I already checked other questions but nothing is worked 我已经检查了其他问题,但没有任何反应

Any idea what could be causing this ? 知道是什么原因造成的吗?

In your constructor replace the binding statement like below 在您的构造函数中,替换如下所示的绑定语句

constructor(props) {
    super(props);
    this.state = { username: '', password: '', datas: '' };
    this.login = this.login.bind(this);
  }

Your login function should be bound in order for it to access the correct this if passed to a Touchable . 您的登录功能应该为了它来访问正确的约束this是否传递到Touchable Could be fixed by either one of these ways: 可以通过以下任何一种方式解决:

 <TouchableOpacity onPress={this.login.bind(this)} ...>

 OR:

 <TouchableOpacity onPress={() => this.login()} ...>

It is basically nothing but just an error returned by firebase in case user enters wrongly formatted email. 基本上没有什么,只是firebase返回的错误,以防用户输入格式错误的电子邮件。 Try entering rightly formatted email id in the signup or login form and you will not get that error from firebase. 尝试在注册或登录表单中输入格式正确的电子邮件ID,您将不会从firebase中收到该错误。

Firebase basically checks at its end whether user entered correct mail id or not while creating new user. Firebase基本上会在创建新用户时检查用户是否输入了正确的邮件ID。

I had a similar issue. 我有一个类似的问题。 For me the issue arose because I had my react-native on "hot reloading", while I was coding. 对我来说,出现这个问题是因为我在编写代码时对“热重载”有自己的反应。

This basically means that I was asking for a variable that wasn't defined, because the constructor wasn't called (the app was live while coding). 这基本上意味着我要的是一个未定义的变量,因为未调用构造函数(该应用在编码时处于活动状态)。

Once you quit/start or just reload the app, then it does define the state (because while initially loading the app it calls the constructor() ). 一旦退出/启动或只是重新加载应用程序,它就会定义状态(因为在最初加载应用程序时,它会调用Constructor())。

Might that have been your issue as well? 可能这也是您的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM