我有一个 Profile
类,如下所示:
class Profile extends React.Component {
state = {
email: '',
userName: '',
userID: ''
};
getData() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('GET', 'http://localhost:8080/user/1');
request.send();
console.log(request.responseText);
}
render() {
return ( <
div >
this.getData(); <
/div>
);
}
}
问题是它没有在控制台中放置任何东西。
虽然 http://localhost:8080/user/1
在浏览器中返回给我这个:
{"userID":1,"passwordHash":"5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5","email":"admin@admin.com"}
如何解决?
最佳答案
我可以设法解决您的问题,您需要使用 {this.getData();}
包装函数调用
可以找到一个例子here
class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {email:'', userName:'', userID:''};
}
getData() {
var request = new XMLHttpRequest();
console.log("Inside getData method");
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('GET', 'https://reqres.in/api/products/3', true);
request.send();
console.log(request.responseText);
}
render() {
return(
<div>
<h2>You sample output</h2>
{this.getData()}
</div>
);
}
}
ReactDOM.render(<Profile />, document.querySelector("#container"))
关于javascript - XMLHttpRequest GET 在 React.js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57519426/