我試圖學習,然後在一個項目中使用反應。我有一個控制器(在軌)輸出JSON:提取數據時我應該使用setInterval嗎?
...
def index
@users = User.order(created_at: :desc)
respond_to do |format|
format.json { render json: @users}
end
end
...
以及從該控制器這樣獲取數據的一個組成部分:
...
fetchData() {
fetch('admin/users.json', {credentials: 'same-origin'})
.then(function(response) {
return response.json()
}).then(function(json) {
this.setState({data: json})
}.bind(this))
.catch(function(ex) {
console.log('parsing failed', ex)
});
};
...
不難呈現這個數據,但什麼是最好的方式允許管理員操縱這些數據? 例如,我必須允許管理員刪除用戶。我知道如何將請求發送到服務器並刪除一個用戶:
...
fetchData() {
fetch('admin/users.json', {credentials: 'same-origin'})
.then(function(response) {
return response.json()
}).then(function(json) {
this.setState({data: json})
}.bind(this))
.catch(function(ex) {
console.log('parsing failed', ex)
});
};
...
但是,如果有兩個管理員相同的列表或表格和刪除用戶的工作?在反應之前,我使用redirect_to /some/index.html,網站被刷新,管理員看到數據庫的當前狀態。現在我試圖避免刷新整個網站,我首先想到的是要獲取數據每1.5秒:
...
tick() {
this.fetchData()
};
componentDidMount() {
setInterval(()=> this.tick(), 500)
};
...
現在管理員使各0.5秒到數據庫的請求,並獲得當前的數據,但此真的很好的解決方案?
那麼,如果你希望網站自動更新服務器的數據,你將不得不設置一個輪詢解決方案(這是你所做的)或使用WebSockets。 –
根據您的要求,我的建議是使用基於WebSockets的解決方案,只要服務器端發生更改,它就會更新管理員屏幕。看看SignalR的基於.Net的解決方案或socket.js的基於JavaScript的解決方案。 – Knitesh
我會說其他2條評論之前說過的話,但是我認爲套接字將會是你的朋友。 –