我是React的新手,我已经阅读了有关如何将React用作独立服务的官方React教程,并且刚刚了解了在Rails应用程序中使用react-rails gem的教程。正是我所需要的。我遇到的问题是我需要为我的React小页面实现某种简单的API轮询,但是我似乎找不到任何关于如何最好地在react-rails中实现它的文档。
在react教程中,它告诉我们pollinterval = 2000
在声明数据源时每2000毫秒轮询一次。我尝试如下实现,但无济于事:
@Records = React.createClass
getInitialState: ->
$.ajax
method: 'GET'
url: '/records'
dataType: 'JSON'
success: (response) ->
records: response
pollinginterval: 2000
...
不幸的是,当我加载页面时,不仅不显示任何内容,而且甚至根本不查询数据库。这使我相信这不是AJAX调用/设置pollinginterval的正确位置,但是在谷歌搜索中没有什么特别有用。
这种方法怎么样?
@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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句