Nik*_*wat 3 javascript reactjs fetch-api
刚开始使用ReactJS和JS,有没有办法将从APIHelper.js获得的JSON返回到App.jsx中的setState dairyList?
我想我不了解React或JS或两者的基本内容.在Facebook React Dev Tools中从未定义dairyList状态.
// 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;
Run Code Online (Sandbox Code Playgroud)
由于fetch是异步,你需要做这样的事情:
componentDidMount() {
APIHelper.fetchFood('Dairy').then((data) => {
this.setState({dairyList: data});
});
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12924 次 |
| 最近记录: |