首页 \ 问答 \ ReactJS componentDidMount和Fetch API(ReactJS componentDidMount and Fetch API)

ReactJS componentDidMount和Fetch API(ReactJS componentDidMount and Fetch API)

刚开始使用ReactJS和JS,有没有办法将从APIHelper.js获得的JSON返回给App.jsx中的setState dairyList?

我认为我不了解有关React或JS或两者的基本知识。 在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;

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;

原文:https://stackoverflow.com/questions/38755092
更新时间:2023-07-30 06:07

最满意答案

将您的点击处理程序更改为mousedown事件:

$(".option").mousedown(function(){
    $("#out").append("<br/>clicked " + $(this).html());
    $("#txtBox").val($(this).html());
});

试试看: http : //jsfiddle.net/CAUQv/

你也可以绑定keyup事件,这样,你就可以检测到实际输入的每一个变化:

$("#txtBox").keyup(function(){
    $("#out").append("<br/>changed value to " + $(this).val());
});

试试看: http : //jsfiddle.net/RZmtz/

文档


Change your click handler to the mousedown event:

$(".option").mousedown(function(){
    $("#out").append("<br/>clicked " + $(this).html());
    $("#txtBox").val($(this).html());
});

Try it: http://jsfiddle.net/CAUQv/

You could also bind the the keyup event instead, that way, you're detecting every change performed by actual typing:

$("#txtBox").keyup(function(){
    $("#out").append("<br/>changed value to " + $(this).val());
});

Try it: http://jsfiddle.net/RZmtz/

Documentation

相关问答

更多
  • 使用下面的代码: