未定义不是this.setState函数 [英] Undefined is not a function this.setState

查看:82
本文介绍了未定义不是this.setState函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的登录页面,一旦按下该按钮,它将执行以下功能:

I created a simple login page, which, once the button is pressed, executes this function :

login = (email, password, navigate) => {
  this.setState({ loginButtonPressed: true });
  firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then(function(user) {
      navigate('Profile');
    })
    .catch(function(error) {
      this.setState({ loginButtonPressed: false });
      Alert.alert(error.toString());
    });
};

一旦调用,它将执行"this.setState({loginButtonPressed:true})",因为按钮会改变形状(标记为已按下).但是出现以下错误:未定义不是this.setState 函数.

Once called, it executes "this.setState({ loginButtonPressed: true })" since the button changes shape (it is marked as pressed). But I get the following error: Undefined is not a function this.setState.

如何解决?感谢您的帮助.

How can this be fixed? Thanks for your help.

推荐答案

问题出在:

.catch(function(error) {
  this.setState({ loginButtonPressed: false });
  Alert.alert(error.toString());
});

您创建一个匿名函数,其中 this 将引用该匿名函数(对象),而不是React对象.

you create an anonymous function where this will reference this anonymous function (Object), not a React Object.

我看到您可以使用箭头功能,所以请像这样修复它:

I see you can use arrow functions, so fix it like:

.catch((error) => {
  this.setState({ loginButtonPressed: false });
  Alert.alert(error.toString());
});

使用箭头功能将引用使用它的上下文.

With arrow function this will reference context in which it is used.

这篇关于未定义不是this.setState函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆