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 ブロックが返されます。その go ブロックを Reagent 関数で直接使用しようとする代わりに、ratom で戻り値を更新することができます。

(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 に答える