我最近一直在使用ReactJS,并且在使用AJAX请求时遇到了设置状态的问题。AJAX请求未在我的React组件中设置this.state.data。
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 (
Comments
{this.state.data}
);
}
};
这是怎么了渲染的成分:
ReactDOM.render(, 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
您是否尝试过你的“成功”函数内部控制台日志?检查当你登录'This'时会发生什么? –
+0
@ZekeDroid - 所以它一直在工作,问题在于渲染功能。显然,我需要映射响应中的元素。谢谢你的提示! –