我最近一直在使用ReactJS,并且在使用AJAX请求时遇到设置状态的问题。
AJAX请求正在服务器上发出请求并接收200个代码,因此我知道API请求运行良好。但是,React组件似乎没有设置this.state.data。
以下是组件代码:
export class Experiences extends React.Component {
constructor() {
super();
this.state = {
data: []
};
}
loadExperiencesFromServer() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: (data) => {
this.setState({
data: data
})
},
error: (xhr, status, err) => {
console.error(this.props.url, status, err.toString());
}
});
}
componentDidMount() {
this.loadExperiencesFromServer();
}
render () {
return (
<div className="commentBox">
<h1>Comments</h1>
<p>{this.state.data}</p>
</div>
);
}
};
这就是我渲染组件的方式:
ReactDOM.render(<Experiences url='/about_me/experiences/' />, document.getElementById('genomics-geek-container'));
当我直接点击API时,我得到了这个回复:
$ http http://127.0.0.1:8000/about_me/experiences/
HTTP/1.0 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Date: Wed, 27 Apr 2016 02:15:40 GMT
Server: WSGIServer/0.2 CPython/3.5.1
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"company": "Mike",
"created": "2016-04-27T01:30:50.425111Z",
"degree": "test",
"description": "test",
"ended": "2016-04-21",
"experience_type": 1,
"is_current_position": true,
"location": "test",
"owner": "geek",
"position": "test",
"started": "2016-04-27"
}
]
}
所以我知道API正在返回数据并且React组件正在我的浏览器上呈现,但由于某种原因没有数据被加载到组件中。我错过了什么?在此先感谢您的帮助!
答案 0 :(得分:3)
你正在失去这方面的背景。
构造函数中的将此绑定到自定义函数
constructor() {
super();
this.state = {
data: []
};
this.loadExperiencesFromServer = this.loadExperiencesFromServer.bind(this)
}