如何处理cljs-ajax响应? [英] How to handle cljs-ajax responses?

查看:138
本文介绍了如何处理cljs-ajax响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从clojurescript前端请求与cljs-ajax到响应JSON的API,但似乎我需要做一些事情,然后才能在cljs中使用它。

I am making a request from a clojurescript frontend with cljs-ajax to an API that responds with JSON but it seems like I need to do something to it before I can use it in cljs.

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

当我初始化我的应用程序状态时,我分配键:all-pieces )

When I initialize my app-state I assign the key :all-pieces (all-pieces)

当我在组件中迭代:all-pieces 获取错误未捕获错误:[object Object]不是ISeqable

When I go to iterate over :all-pieces in a component I get the error Uncaught Error: [object Object] is not ISeqable.

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

编辑re Pratley:

Edited re Pratley:

all-pieces 的状态 {} ,看到什么错?

The code below now results in the state of all-pieces being {}, see anything wrong?

;; -------------------------
;; 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)))


推荐答案

c $ c>:all-peices 添加到(all-pieces)的结果。
ajax-success-handler 应该设置:all-peices
(all-pieces)的结果是启动异步调用的结果,而不是响应。处理程序是在响应到达时调用的。

Don't set :all-peices to the result of (all-pieces). The function ajax-success-handler should set :all-peices instead. The result of (all-pieces) is the result of starting the asynchronous call, not the response. The handler is what gets called when the response arrives.

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

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

Does not do any swapping, as swap! needs to be in parens... it is just a function that returns pcs. Consider promoting it to a named function so you can test it separately:

(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)

这篇关于如何处理cljs-ajax响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆