我正在使用React并尝试使用API中的数据填充ImageGrid。没有与获取数据没有问题,但不知何故,我不能把我的状态与responseData
React无法设置状态
我可以显示数据,同时我从API响应,但我不能把我的状态......
componentWillMount()
{
this.state = {
content: ''
};
this.loadContent();
}
loadContent()
{
ApiService.getTweets(topic,numberOfElements,offset).then((responseData) => {
console.log("Data is here",responseData); //<---------- HERE
this.setState({
content: responseData
});
})
console.log("Data is not here",this.state.content); //<---------- HERE
}
在这里,我得到的数据:
class ApiService {
static getTweets() {
return fetch("https://MyURL", {
method: 'get'
})
.then((resp) => resp.json())
.then(function(data) {
return data;
}).catch(function(error) {
console.log(error);// Error :(
});
}
}
export default ApiService;
两个原因(至少):setState不会立即设置状态,并且您正试图在调用之前访问它 - 您将其设置为异步回调。 –
[更改状态点击反应js]可能的重复(https://stackoverflow.com/questions/41278385/change-state-on-click-react-js) –
反应文档建议在使用时在构造函数中设置状态ES6课程。但是这应该会导致这个问题。 –