我正在做一个基本的React应用程序,其数据来自我的api。但是当AJAX成功后我做this.setState({})
时状态不会更新。在render
方法中,state.events为空。成功的AJAX请求后状态没有更新
我在做什么错?
import React, {PropTypes, Component} from 'react';
import axios from 'axios';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
events: []
};
}
componentDidMount() {
axios.get('http://localhost:4000/api/v1/events')
.then(function (response) {
this.setState({events: response.data});
})
.catch(function (error) {
console.warn(error);
});
}
render() {
// this.state.events keeps being an empty array []
return (
<div className="home">
{
this.state.events.map((month) => {
console.log(month)
})
}
</div>
);
}
}
export default App;
OMG谢谢,我忘了经典的'这个混乱'在JS :) – olefrank