【问题标题】:ReactJS componentDidMount and Fetch APIReactJS componentDidMount 和 Fetch API
【发布时间】:2016-12-09 20:29:37
【问题描述】:

刚开始使用ReactJS和JS,有没有办法将APIHelper.js获取的JSON返回到App.jsx中的setStatedai​​ryList?

我认为我不了解 React 或 JS 或两者的基本知识。 DairyList 状态从未在 Facebook React 开发工具中定义。

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

【问题讨论】:

  • 您的APIHelper.js 文件在语法上是否正确?修复后,另一件事:APIHelper.fetchFood 是异步的。
  • @zerkms 谢谢,刚刚注意到 fetchFood 的右大括号在 var url 之后。有没有更好的方法来获取数据,等待响应然后从那里开始?

标签: javascript reactjs fetch-api


【解决方案1】:

由于fetch 是异步的,您需要执行以下操作:

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

【讨论】:

  • 甜蜜!感谢您的回答,它有帮助。
  • @Nikkawat 太棒了!如果没有其他问题,您应该单击此答案旁边的复选标记。
【解决方案2】:

有效!根据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;

【讨论】:

  • FWIW,你不应该需要.bind(this) 这会自动发生在“胖箭头”(() => {} 风格。
  • 没有.bind(this) 我收到错误Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
  • 这很有趣。 docs 和我的经验并非如此,但无论如何都行得通!
猜你喜欢
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 2015-09-03
  • 2017-05-16
  • 2015-07-06
  • 2019-05-20
  • 2023-04-09
相关资源
最近更新 更多