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
最满意答案
将您的点击处理程序更改为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/
文档
jQuery.mousedown
- http://api.jquery.com/mousedown/jQuery.keyup
- http://api.jquery.com/keyup/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
jQuery.mousedown
- http://api.jquery.com/mousedown/jQuery.keyup
- http://api.jquery.com/keyup/
相关问答
更多-
按钮点击处理程序不工作(button click handler not working)[2023-09-09]
使用下面的代码: