不能在提取调用中使用成员函数

我从fetch调用中得到响应,并且我正在尝试检查响应是否与某种错误相对应,如果我的数据库中已经存在用户名或发送的电子邮件,则服务器可能会响应我。如果是这种情况,我尝试使用类的成员函数向用户显示错误消息。但是当我尝试使用成员函数时,出现错误: 未处理的拒绝(TypeError):无法读取未定义的属性'showValidationErr'。

我认为在那种情况下我不能使用成员函数,当我从服务器中发现错误时如何调用成员函数?

class RegisterBox extends React.Component {
  constructor(props) {
      super(props);
      this.state = {username: "",email: "",password: "",confirmPassword: "",errors: [],pwdState: null};
    }

    showValidationErr(elm,msg) {
      this.setState((prevState) => ( {errors: [...prevState.errors,{elm,msg} ] } ) );
    }

    submitRegister(e) {
      fetch("http://localhost:8080/register?user=" + this.state.username + "&psw=" + this.state.password + "&email=" + this.state.email)
            .then(function (respond) {
              return respond.text()
              .then(function(text) {
                if (text === "RegisterError : username") {
                  this.showValidationErr("username","username allready taken.");
                }
                if (text === "RegisterError : email") {
                  this.showValidationErr("email","email allready used.");
                }
              })
            });
    }
  }
q474136201 回答:不能在提取调用中使用成员函数

在这种情况下,this指的是您传递给function()的匿名回调then()。请尝试使用箭头函数语法代替this作为周围的上下文。

        .then((respond) => {
          return respond.text()
          .then((text) => {
            if (text === "RegisterError : username") {
              this.showValidationErr("username","username allready taken.");
            }
            if (text === "RegisterError : email") {
              this.showValidationErr("email","email allready used.");
            }
          })
,

我找到了纠正方法。我需要添加行“ var that = this;”在我的函数开始处,并使用“ that.showValidationErr();”代替。

本文链接:https://www.f2er.com/3163848.html

大家都在问