ReactJS componentDidMount和Fetch API [英] ReactJS componentDidMount and Fetch API
本文介绍了ReactJS componentDidMount和Fetch API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
刚开始使用ReactJS和JS,有没有办法将从APIHelper.js获得的JSON返回到App.jsx中的setState dairyList?
Just started using ReactJS and JS, is there a way to return the JSON obtained from APIHelper.js to setState dairyList in App.jsx?
我想我不了解React或JS或两者的基本内容。在Facebook React Dev Tools中从未定义dairyList状态。
I think I'm not understanding something fundamental about React or JS or both. The dairyList state is never defined in Facebook React Dev Tools.
// App.jsx
export default React.createClass({
getInitialState: function() {
return {
diaryList: []
};
},
componentDidMount() {
this.setState({
dairyList: APIHelper.fetchFood('Dairy'), // want this to have the JSON
})
},
render: function() {
...
}
// APIHelper.js
var helpers = {
fetchFood: function(category) {
var url = 'http://api.awesomefoodstore.com/category/' + category
fetch(url)
.then(function(response) {
return response.json()
})
.then(function(json) {
console.log(category, json)
return json
})
.catch(function(error) {
console.log('error', error)
})
}
}
module.exports = helpers;
推荐答案
由于 fetch
是异步的,你需要做类似的事情这个:
Since fetch
is async you'll need to do something like this:
componentDidMount() {
APIHelper.fetchFood('Dairy').then((data) => {
this.setState({dairyList: data});
});
},
这篇关于ReactJS componentDidMount和Fetch API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文