React-Rails API轮询

时间:2016-03-17 04:47:04

标签: ruby-on-rails ruby reactjs react-rails

我是React的新手,我已经通过the official React tutorials了解了如何将React用作独立服务,并且在Rails应用程序中使用react-rails gem时已经通过了this tutorial在大多数情况下,我已经适应了我所需要的。我遇到的问题是我需要为我的小React页面实现某种简单的API轮询,但我似乎无法找到关于如何在react-rails中最好地实现它的文档。

在反应教程中,它告诉我们在声明数据源每2000毫秒轮询一次源时使用pollinterval = 2000。我尝试按如下方式实现,但无济于事:

@Records = React.createClass
    getInitialState: ->
      $.ajax
        method: 'GET'
        url: '/records'
        dataType: 'JSON'
        success: (response) ->
          records: response
      pollinginterval: 2000
    ...

不幸的是,当我加载页面时,不仅没有内容实际显示,而且似乎根本不是查询数据库 - 甚至最初。这让我相信这不是AJAX调用/设置轮询间隔的正确位置,但我的谷歌搜索中没有任何内容特别有用。

2 个答案:

答案 0 :(得分:2)

这种做法怎么样?

@Records = React.createClass
  getInitialState: ->
    # `this.state.records` is empty now, but will be loaded by AJAX
    {
      records: [] 
    }

  componentDidMount: ->
    # Ping every 2s
    @_recordsInterval = setInterval =>
        @_loadRecords()
      , 2000
    # Load initial data: 
    @_loadRecords()

  componentWillUnmount: -> 
    # clean up loose ends: 
    clearInterval(@_recordsInterval)
    @_recordsRequest?.abort()

  # ...

  _loadRecords: ->
   # Fetch records from the server and store it as `this.state.records`
   @_recordsRequest = $.get "/records", (data) => 
     @setState(records: data)

答案 1 :(得分:0)

我建议您在componentDidMount而不是getInitialState中执行ajax调用。

查看本教程以加载ajax数据。 https://facebook.github.io/react/tips/initial-ajax.html