2

我正在尝试从 Clojurescript/Reagent 中的 API 调用呈现 JSON 数据。当我使用时,js/alert我看到了我期望的 json:["Sue" "Bob"]

(defn- call-api [endpoint]
  (go
    (let [response (<! (http/get endpoint))]
      (:names (:body response)))))

;; -------------------------
;; Views

(defn home-page []
  [:div (call-api "/api/names")])

这就是我引用库的方式(以防出现问题)。

(ns myapp.core
    (:require [reagent.core :as reagent :refer [atom]]
              [reagent.session :as session]
              [cljs-http.client :as http]
              [cljs.core.async :refer [<! >!]]
              [secretary.core :as secretary :include-macros true]
              [accountant.core :as accountant])
    (:require-macros [cljs.core.async.macros :refer [go]]))

但是当我将它记录到控制台时,我得到了一个看起来与 API 响应完全不同的长哈希。浏览器呈现“00000000000120”。

  • 为什么这些结果不同?(浏览器、警报窗口、控制台消息)
  • 如何让我在警报窗口中看到的内容呈现在页面上?
4

1 回答 1

3

当您调用call-api它时,它将返回一个 go 块。与其尝试直接在您的 Reagent 函数中使用该 go 块,您可以改为更新随机数中的返回值。

(def app-state (atom)) ;; ratom

(defn- call-api [endpoint]
  (go
    (let [response (<! (http/get endpoint))]
      (reset! app-state (:names (:body response))))))

(defn home-page []
  [:div @app-state])

(defn main []
  (call-api))
于 2016-02-09T00:28:41.410 回答