繁体   English   中英

ReactJS componentDidMount和Fetch API

[英]ReactJS componentDidMount and 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;

由于fetch是异步的,你需要做这样的事情:

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

有用! 根据Jack的回答做了更改,在componentDidMount()中添加了.bind(this) )并更改了fetch(url)return fetch (url)

谢谢! 我现在看到State > dairyList:Array [1041],其中包含我需要的所有元素

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM