Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js can';t在fetch调用中使用成员函数_Node.js_Reactjs_Fetch - Fatal编程技术网

Node.js can';t在fetch调用中使用成员函数

Node.js can';t在fetch调用中使用成员函数,node.js,reactjs,fetch,Node.js,Reactjs,Fetch,我从一个fetch调用中得到一个响应,我试图检查该响应是否与某种错误相对应。如果我的数据库中已经存在用户名或发送的电子邮件,我的服务器可能会响应我。如果是这种情况,我尝试使用类的成员函数向用户显示错误消息。但是当我尝试使用我的成员函数时,我得到了一个错误: 未处理的拒绝(TypeError):无法读取未定义的属性“showValidationError” 我认为在这种情况下我不能使用成员函数,当我从服务器上发现错误时,我如何调用我的成员函数 class RegisterBox extends R

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

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

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.");
                }
              })
            });
    }
  }

在此上下文中,
this
指的是传递给
then()
的匿名回调
function()
。尝试改用箭头函数语法,该语法将
this
作为周围上下文

。然后((响应)=>{
返回respond.text()
。然后((文本)=>{
如果(文本==“注册表错误:用户名”){
showValidationErr(“用户名”,“用户名已准备就绪”);
}
如果(文本==“注册表错误:电子邮件”){
showValidationErr(“email”,“email allready used”);
}
})

我发现了如何更正它。我需要在函数开头添加行“var that=this;”,并使用“that.showValidationErr();”相反。

重复此选项是否回答了您的问题?使用箭头函数进行promise resolve回调。
。然后
应使用箭头函数,以便
可以引用
注册表框
组件。