Ajax GET with Reagent

时间:2015-05-05 18:25:14

标签: ajax clojurescript reagent

我正在从我的Reagent应用程序执行Ajax GET,从数据库加载一些东西。

我不完全确定将这样的ajax调用的结果传递给我的页面的最佳方法是什么,考虑到如果我把它放在一个原子中,那么当一个原子被取消引用时,Reagent会自动重新渲染一个组件,意味着我得到了无限的ajax调用序列。

对于某些代码,

(def matches (atom nil))

(defn render-matches [ms]
  (reset! matches (into [:ul] (map (fn [m] ^{:key m}[:li m])
                                   (walk/keywordize-keys (t/read (t/reader :json) ms)))))

此功能基本上创建了[:ul [:li "Stuff here"] [:li "And here"]]

我想在我的页面上显示,现在有以下代码。

(defn standings-page []
  (GET "/list-matches"
       {:handler render-matches})
  @matches)

1 个答案:

答案 0 :(得分:12)

我认为最好只保存原子中的数据并将HTML作为组件逻辑的一部分生成。

最好在渲染阶段之外触发AJAX调用,例如,在组件安装之前,或者作为事件的结果(例如,点击按钮)。

像这样:

(def matches (atom nil))
(defn component []
  (let [get-stuff (fn [] (GET "/..." :handler (fn [response] 
                           (reset! matches (:body response))))]
    (get-stuff) <-- called before component mount
    (fn []
      [:ul
        (for [m match]
          ^{:key ...} 
          [:li ...])])))

这在this post中称为form-2。