简体   繁体   English

使用react.js从api函数获取json数据

[英]get json data from api function using react.js

How can I get the json data from apiUrl? 如何从apiUrl获取json数据? Need some help writing the function 需要一些帮助编写函数

changeUrl: function(evt){
        this.setState({
          value: evt.target.value,
          apiUrl: "https://test.holmusk.com/food/search?q=" + evt.target.value
        });
      },

      getJson: function() {

      },

Your code is a bit confusing because it's hard to tell why you're setting apiURL in setState, when I assume you need to call that URL to get the Json data. 您的代码有点混乱,因为当我假设您需要调用该URL来获取Json数据时,很难说出为什么要在setState中设置apiURL。 The commenter makes a good point about setting up a data-retrieval architecture using a library like Redux. 评论者很好地说明了使用Redux之类的库来建立数据检索架构。 However, if you want to just do a plain-vanilla Javascript call, you could do something like below. 但是,如果您只想进行普通的Javascript调用,则可以执行以下操作。 It's hard to tell if you need the Json results in your component's state, but I'm guessing you do, so I rearranged the code with that assumption in mind. 很难确定您是否需要组件状态的Json结果,但是我猜您确实需要这样做,因此我在考虑到这一假设的情况下重新排列了代码。

    changeUrl: function(evt){
            getJson(evt.target.value);
    },

    getJson: function(newVal) {
        var request = new XMLHttpRequest();
        request.open('GET', "https://test.holmusk.com/food/search?q=" + newVal, true);
            request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');    
            //this callback gets called when the server responds to the ajax call            
            request.onreadystatechange = function(){
                if (request.readyState === 4 && request.status === 200){
                    var returnedJson = JSON.parse(request.responseText);
                    //this is where you would want to run setState if you need the returned Json for it.
                    setState({newJson: returnedJson});
                }
                else if (request.readyState === 4 && request.status !== 200){
                    alert('error');
                }           
            };      
            request.send();
    }

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

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