【问题标题】:undefinend is not a function this.setState react nativeundefinend 不是函数 this.setState 反应原生
【发布时间】:2019-06-25 05:30:49
【问题描述】:

我正在开发一个反应原生应用程序。当我尝试执行以下代码时出现错误。但是同一文件其他部分的 setStates 工作正常。

未定义不是 功能(评估'this.setState({firebaseMessages:“错误 密码"})

 .catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === "auth/wrong-password") {
      //alert("Wrong password.");
      this.setState({ firebaseMessages: "Wrong password" });
      this.setState({ isModalVisibleFirebase: true });
      this.setState({ loading: false })
      return;
    } else {
      alert(errorMessage);
      return;
    }
    console.log(error);
  }

【问题讨论】:

  • 你在构造函数中声明了firebaseMessages状态吗?

标签: android react-native undefined setstate


【解决方案1】:

你可能需要绑定你的回调函数,试试这个:

catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === "auth/wrong-password") {
        //alert("Wrong password.");
        this.setState({ firebaseMessages: "Wrong password" });
        this.setState({ isModalVisibleFirebase: true });
        this.setState({ loading: false })
        return;
    } else {
        alert(errorMessage);
        return;
    }
    console.log(error);
}.bind(this)) // change this line

或者,您可以使用 ES6 箭头函数,如下所示:

catch((error) => {  // change this line
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === "auth/wrong-password") {
        //alert("Wrong password.");
        this.setState({ firebaseMessages: "Wrong password" });
        this.setState({ isModalVisibleFirebase: true });
        this.setState({ loading: false })
        return;
    } else {
        alert(errorMessage);
        return;
    }
    console.log(error);
})

【讨论】:

    【解决方案2】:

    如果你使用 ES5 函数定义你的 this 范围会改变,使用箭头语法来保持 this 范围。

    所以现在你应该使用.catch((error) => { 而不是.catch(function (error){

    .catch((error) => {
        var errorCode = error.code;
        var errorMessage = error.message;
    
        if (errorCode === "auth/wrong-password") {
          //alert("Wrong password.");
          this.setState({ firebaseMessages: "Wrong password" });
          this.setState({ isModalVisibleFirebase: true });
          this.setState({ loading: false })
          return;
        } else {
          alert(errorMessage);
          return;
        }
        console.log(error);
      }
    

    【讨论】:

      【解决方案3】:

      简单的解决方案是,将this 分配给某个变量,然后使用该变量调用setState

      const _this = this; //write this before fetch method
      

      然后像这样使用,

      _this.setState({ firebaseMessages: "Wrong password" });
      

      【讨论】:

        猜你喜欢
        • 2015-08-06
        • 2015-09-11
        • 2018-02-27
        • 2019-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多