![](/img/trans.png)
[英]TypeError: Cannot read property 'length' of undefined in react.js
[英]TypeError: Cannot read property 'username' of undefined React.js
好吧,我有一個 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)
}
});
}
如果我單擊一個按鈕,則應執行 function getData()
。 但是,如果這個 function 被執行,我會收到這個錯誤TypeError: Cannot read property 'username' of undefined
in the browser。
這就是我調用 function 的方式:
<input type="input" value={this.state.username} onChange={this.handleChangeUsername} className="form-control" placeholder="Email" />
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.