如何处理cljs-ajax响应?

时间:2016-03-10 02:43:46

标签: ajax clojure clojurescript

我正在使用cljs-ajax向clojurescript前端发出一个请求,该请求使用JSON进行响应,但似乎我需要先做一些事情才能在cljs中使用它。

(defn all-pieces []
  (GET "/art/pieces" {:handler ajax-success-handler}))

初始化应用状态时,我会分配密钥:all-pieces (all-pieces)

当我在组件中迭代:all-pieces时,我收到错误Uncaught Error: [object Object] is not ISeqable

(defn pieces-component []
  [:ul (for [piece (:all-pieces @app-state)]
         [:li (art-piece piece)])])

Pratley编辑:

下面的代码现在导致all-pieces状态为{},看错了什么?

;; -------------------------
;; Remote Data

(defn all-pieces [handler]
  (GET "/art/pieces" {:handler handler}))

;; -------------------------
;; State Management

(def app-state (atom
  {:doc {}
    :saved? false
    :page-state {}
    :all-pieces {}}))


(defn set-pieces-fresh []
  (all-pieces (fn [pcs] swap! app-state assoc :all-pieces pcs)))

1 个答案:

答案 0 :(得分:2)

请勿将:all-peices设置为(all-pieces)的结果。 函数ajax-success-handler应该设置:all-peices(all-pieces)的结果是启动异步调用的结果,而不是响应。处理程序是响应到达时调用的。

(fn [pcs] swap! app-state assoc :all-pieces pcs)

不做任何交换,作为交换!需要在parens ......它只是一个返回pcs的函数。考虑将其提升为命名函数,以便您可以单独测试它:

(def app-state
  (atom {:all-pieces {}}))

(defn pieces-handler [pcs]
  (swap! app-state assoc :all-pieces pcs))

(defn fetch-pieces []
  (GET "/art/pieces" {:handler pieces-handler}))

(fetch-pieces)