我是React的新手,所以我知道我可能做的并不正确。
我试图在回调中调用setStatus进行onreadystatechange,但在浏览器中出现错误。该代码对服务器执行AJAX调用,以查看数据库中是否已存在建议的用户名。返回时,将执行onreadystatechange。我正在尝试为用户名设置新的错误消息(如果已经存在)。
这是我的状态数据:
const initialState = {
firstname: "",
lastname: "",
username: "",
password: "",
email: "",
firstnameError: "",
lastnameError: "",
usernameError: "",
passwordError: "",
emailError: ""
};
class SignUpForm extends Component {
constructor() {
super();
this.state = initialState;
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.checkUserName = this.checkUserName.bind(this);
this.checkEmail = this.checkEmail.bind(this);
this.validateForm = this.validateForm.bind(this);
}
这是我在变更处理程序中更新以下形式的字段的状态的地方:
handleChange(e) {
let target = e.target;
let value = target.value;
let name = target.name;
if (name === "username") {
value = value.toUpperCase();
}
this.setState({
[name]: value
});
}
这是我在浏览器中遇到错误的例程。发生错误的行在下面的行中带有注释。
checkUserName() {
let usernameError = "";
let element = "";
let checkNameResponse = "";
let checkNameMessage = "";
let request = "";
let url = "";
let userName = "";
let requestData = "";
let checkNameResponseJSON = "";
request = new XMLHttpRequest();
if (request == null) alert("Unable to create checkDBForUSerNameRequest");
else {
url = "/php/CheckUsername.php";
userName = escape(document.getElementById("username").value);
requestData = JSON.stringify({
username: userName
});
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
checkNameResponseJSON = JSON.parse(request.responseText);
checkNameResponse = checkNameResponseJSON.returncode;
checkNameMessage = checkNameResponseJSON.message;
element = document.getElementById("SignupIcon");
element.className = "displayIcon";
if (checkNameResponse === 0) {
element = document.getElementById("SignupIconFile");
element.src = "/images/YesButton.png";
element.alt = "Available";
this.setState({ usernameError: "" });
} else {
element = document.getElementById("SignupIconFile");
element.src = "/images/NoButton.png";
element.alt = "Not Available";
usernameError = checkNameMessage;
this.setState({ usernameError: usernameError }); // BROWSER ERROR
}
}
};
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(requestData);
}
}
这是来自浏览器错误的文本:
0: Object doesn't support property or method 'setState'
有什么想法为什么会发生或如何解决?
答案 0 :(得分:3)
您需要使用.bind或arrow函数绑定onreadystatechange函数,因为执行该函数时,它需要访问引用类上下文的正确this
值。
request.onreadystatechange = function() {
// all logic here
}.bind(this)
或
request.onreadystatechange = () => {
//all logic here
}
答案 1 :(得分:3)
错误是因为您使用的是request.onreadystatechange = function() {}
而不是request.onreadystatechange = () => {}
或request.onreadystatechange = function() {}.bind(this)
使用function()
时,this
的范围会改变。
请记住,function() {}
和() => {}
不同。
但是function(){}.bind(this)
和() => {}
相同。