ReactJS componentDidMount and Fetch API

 ̄綄美尐妖づ 提交于 2019-12-09 18:58:27

问题


Just started using ReactJS and JS, is there a way to return the JSON obtained from APIHelper.js to setState dairyList in App.jsx?

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;

回答1:


Since fetch is async you'll need to do something like this:

componentDidMount() {
  APIHelper.fetchFood('Dairy').then((data) => {
    this.setState({dairyList: data});
  });
},



回答2:


It works! Made changes according to Jack's answer, added .bind(this) in componentDidMount() and changed fetch(url) to return fetch (url)

Thanks! I now see State > dairyList: Array[1041] with all the elements I need

// App.jsx
export default React.createClass({
  getInitialState: function() {
    return {
      diaryList: []
    };
  },
  componentDidMount() {
    APIHelper.fetchFood('Dairy').then((data) => {
      this.setState({dairyList: data});
    }.bind(this));
  },
  render: function() {
   ... 
  }


// APIHelper.js
var helpers = {
  fetchFood: function(category) {
    var url = 'http://api.awesomefoodstore.com/category/' + category

    return 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;


来源:https://stackoverflow.com/questions/38755092/reactjs-componentdidmount-and-fetch-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!