[英]TypeError: Cannot read property 'username' of undefined React.js
Well I have a React.js application.好吧,我有一个 React.js 应用程序。
constructor(props){
super(props);
this.state = {
password:'',
username:''
}
this.handleChangePassword = this.handleChangePassword.bind(this)
this.handleChangeUsername = this.handleChangeUsername.bind(this)
this.getData = this.getData.bind(this)
}
handleChangePassword(event) {
this.setState({password: event.target.value});
}
handleChangeUsername(event) {
this.setState({username: event.target.value});
}
getData() {
$.ajax({
type: 'GET',
url: `/home/data`,
dataType: 'json',
//whatever you need
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
},
success: function(xhr){
console.log(xhr.status)
}
});
}
If I click on a button the function getData()
should be executed.如果我单击一个按钮,则应执行 function getData()
。 But if this function gets executed I'm getting this error TypeError: Cannot read property 'username' of undefined
in the browser.但是,如果这个 function 被执行,我会收到这个错误TypeError: Cannot read property 'username' of undefined
in the browser。
This is how I call the function:这就是我调用 function 的方式:
<input type="input" value={this.state.username} onChange={this.handleChangeUsername} className="form-control" placeholder="Email" />
the this
is referring to the beforeSend function, try arrow function to get rid of it this
是指之前发送function,尝试箭头function摆脱它
beforeSend: (xhr) => { // change to arrow
xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.