gpt4 book ai didi

clojure - 谷歌图表 CLJS Clojure

转载 作者:行者123 更新时间:2023-12-02 16:48:02 25 4
gpt4 key购买 nike

我试图适应这个example在谷歌图表中。要重新构建框架,试剂。我想创建一个基于订阅的实时图表。我用一个简单的计数器 =+-1 进行了测试。

我收到错误:断言失败:渲染必须是一个函数,而不是 nil
(ifn?渲染乐趣)

(defn draw-demo-chart 
[d]
(let [[columns vectors options chart] (r/children d)
data (new js/google.visualization.DataTable)]
(doall ;gotta keep the doall on maps. lazy sequence...
(map (fn [[type name]]
(.addColumn data type name)) columns))
(.addRows data vectors)
(.draw chart data options)
(.load js/google "visualization" "1" (clj->js {:packages ["corechart" "orgchart" "calendar" "map" "geochart"]}))
(.setOnLoadCallback js/google draw-demo-chart)
))


(defn draw-demo-chart-container
[]
(let [count (re-frame/subscribe [:count])
columns (reaction [["date" "X"] ["number" "Y"]])
vectors (reaction (clj->js [[(new js/Date "07/11/14") 145] [(new js/Date "07/12/14") 15]
[(new js/Date "07/13/14") 23] [(new js/Date "07/14/14") 234]]))
options (reaction (clj->js {:title (str @count)}))
chart (reaction (new js/google.visualization.LineChart (.getElementById js/document "linechart"))) ]
(fn []
[draw-demo-graph @columns @vectors @options @chart])))

(def draw-demo-graph
(r/create-class {:reagent-render draw-demo-chart
:component-did-mount draw-demo-chart
:component-did-update draw-demo-chart}))

最佳答案

使用 Google Charts API 存在几个挑战:

  1. 它异步加载,并且只能在准备好时使用。

我建议使用一个标志来记录 API 是否准备好,这样即使在组件安装后加载 API,它也可以渲染。

(defonce ready?
(reagent/atom false))

(defonce initialize
(do
(js/google.charts.load (clj->js {:packages ["corechart"]}))
(js/google.charts.setOnLoadCallback
(fn google-visualization-loaded []
(reset! ready? true)))))
  • 您需要在 HTML 元素上调用 draw:
  • 仅当组件已安装时,HTML 元素才会存在。您可以使用 ref 方便地获取 HTML 元素(否则您需要在安装时保存对 in 的引用,或搜索它)。

    (defn draw-chart [chart-type data options]
    [:div
    (if @ready?
    [:div
    {:ref
    (fn [this]
    (when this
    (.draw (new (aget js/google.visualization chart-type) this)
    (data-table data)
    (clj->js options))))}]
    [:div "Loading..."])])

    每当任何输入发生变化时,您都需要重新绘制(上面的 ref 示例就是这样做的)。

  • 设置数据源
  • 我建议一种获取数据源的便捷方法:

    (defn data-table [data]
    (cond
    (map? data) (js/google.visualization.DataTable. (clj->js data))
    (string? data) (js/google.visualization.Query. data)
    (seqable? data) (js/google.visualization.arrayToDataTable (clj->js data))))
  • 使用它
  • 现在您可以将图表与 react 值一起使用!

    [draw-chart
    "LineChart"
    @some-data
    {:title (str "Clicks as of day " @day)}]

    完整代码 list 位于 https://github.com/timothypratley/google-chart-example

    关于clojure - 谷歌图表 CLJS Clojure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45965325/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com