【问题标题】:How to make an API call using Meteor and React如何使用 Meteor 和 React 进行 API 调用
【发布时间】:2017-10-28 14:06:16
【问题描述】:

我有这个 Meteor 方法:

Meteor.methods({

'RESTcall':function () {
        this.unblock();
        return Meteor.http.call("GET", "http://www.viaggiatreno.it/viaggiatrenonew/resteasy/viaggiatreno/soluzioniViaggioNew/228/458/2017-05-31T00:00:00");}});

还有一个 React Component.jsx,在渲染函数中有一个按钮,它调用这样的函数:

   search(){
      Meteor.call("RESTcall", (error, response)=>{
                 console.log(response); //this works
                 this.setState({results: response}); //this throws an exception
            }
      });
}

问题是如何使用回调函数中的响应来呈现其内容。

提前致谢。

【问题讨论】:

  • 在您的代码中 console.log(results) 但在任何地方都没有定义 resultsconsole.log(response) 的输出是什么?又抛出了什么样的异常?
  • 抱歉,console.log (response) 有效,它是 JSON 响应
  • 你能提供例外吗?你的电话看起来不错。 This.setState 应该可以工作,因为您使用的是箭头函数。我猜问题出在 http 调用上,可能是 CORS 问题。

标签: javascript api reactjs meteor methods


【解决方案1】:

你可以做一个小的改变,如下所示。我还没有测试过,但我认为它应该可以工作。

 search(){
      var that = this; /*Since the setState method in this is accessible here*/
      Meteor.call("RESTcall", (error, response)=>{
                 console.log(response); 
                 that.setState({results: response});
            }
      });

【讨论】:

  • 他正在使用箭头函数,所以这应该绑定到反应类并且 this.setState 应该可以工作。
猜你喜欢
  • 2021-07-08
  • 1970-01-01
  • 2017-03-29
  • 2018-04-24
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2015-08-07
  • 2020-12-15
相关资源
最近更新 更多