好吧,我有一个 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)
}
});
}
如果我点击一个按钮,函数getData()
应该被执行。但是,如果执行此函数,我会在浏览器中收到此错误 TypeError: Cannot read property 'username' of undefined
。
这就是我调用函数的方式:
<input type="input" value={this.state.username} onChange={this.handleChangeUsername} className="form-control" placeholder="Email" />
答案 0 :(得分:0)
this
指的是 beforeSend 函数,尝试使用箭头函数来摆脱它
beforeSend: (xhr) => { // change to arrow
xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
},