首页 > 解决方案 > 如何使用试剂在 Clojurescript 中进行定时页面刷新?

问题描述

我正在编写一个 Clojurescript SPA,它需要定期(可能每 30 秒一次,可能每分钟一次)轮询服务器并获取一些更新的数据。

我应该如何在 Clojurescript 中使用 Reagent(React 框架)执行此操作?

我只是使用 Javascript 的低级 setTimeout() 还是在 Clojurescript / React 中有更惯用的方法来做到这一点?

标签: reactjsclojurescriptreagent

解决方案


试剂示例很好地说明了这一点:

(ns simpleexample.core
  (:require [reagent.core :as r]))

(defonce timer (r/atom (js/Date.)))

(defonce time-color (r/atom "#f34"))

(defonce time-updater (js/setInterval
                       #(reset! timer (js/Date.)) 1000))

re-frame 文档中的第一个示例类似:

;; -- Domino 1 - Event Dispatch -----------------------------------------------

(defn dispatch-timer-event
  []
  (let [now (js/Date.)]
    (rf/dispatch [:timer now])))  ;; <-- dispatch used

;; Call the dispatching function every second.
;; `defonce` is like `def` but it ensures only one instance is ever
;; created in the face of figwheel hot-reloading of this file.
(defonce do-timer (js/setInterval dispatch-timer-event 1000))

与 Clojure 一样,在许多情况下,我们从主机平台重用现有机器,而不用包装器伪装(或用新代码重新发明它)。


推荐阅读