3 回答

TA貢獻1843條經驗 獲得超7個贊
將函數更改為箭頭函數或將其作為函數中的參數傳遞,然后在函數中使用 this.setState({}) 像這樣
xhr.onreadystatechange = function(this) {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.responseText);
this.setState({name: xhr.responseText});
}
}

TA貢獻1840條經驗 獲得超5個贊
確保引用正確的對象或使用箭頭函數
componentDidMount() {
//AJAX REQUEST
var that = this;//make sure you reference the right object
const url = 'http://localhost:8080/ping';
const xhr = new XMLHttpRequest();
xhr.responseType = 'text';
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.responseText);
that.setState({name: xhr.responseText});
}
}
xhr.open("GET", url);
xhr.send();
}
添加回答
舉報