【问题标题】:get json data from api function using react.js使用 react.js 从 api 函数获取 json 数据
【发布时间】:2016-08-02 02:07:09
【问题描述】:

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

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

      getJson: function() {

      },

【问题讨论】:

  • 您不会“使用”响应来从 API 获取数据。 React 只是视图组件。您可以使用 javascript 进行 HTTP 调用以从您的 API 获取数据。如果您对数据做了很多工作,那么我建议您研究一下flux/redux/alt。那里有很多 http 库可供使用。我喜欢使用github.com/mzabriskie/axios 或者你甚至可以只使用 $.get(apiUrl, function(data) {});

标签: javascript json api reactjs


【解决方案1】:

您的代码有点混乱,因为当我假设您需要调用该 URL 来获取 Json 数据时,很难说出您为什么要在 setState 中设置 apiURL。评论者提出了一个很好的观点,即使用像 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();
    }

【讨论】:

    猜你喜欢
    • 2019-06-27
    • 1970-01-01
    • 2023-01-16
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多