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

get json data from api function using react.js

本文关键字:获取 json 数据 函数 api react js 使用      更新时间:2024-04-24

如何从apiUrl获取json数据?需要一些帮助来编写函数

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

您的代码有点令人困惑,因为很难判断为什么要在setState中设置apiURL,而我认为您需要调用该URL来获取Json数据。评论者提出了一个很好的观点,即使用像Redux这样的库来建立数据检索体系结构。然而,如果您只想执行一个普通的Javascript调用,您可以执行以下操作。很难说您是否需要组件状态下的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();
    }