3

我们正在使用带有 clojurescript 和 Reagent 的 chart.js。现在我知道 Chart.js 有一个 chart.update() 方法来用新数据更新图表。所以问题是,我该如何设置我的组件,以便它在 :reagent-render 上呈现图表,但可能会得到 :component-will-update 来调用 chart.update() 方法?

基本上,有没有办法获取从 :component-will-update 函数中的 :reagent-render 函数创建的图表的句柄?

4

1 回答 1

1

在这种情况下,您遵循的通常模式是将有状态/可变对象包装在 React 组件中并使用 React 的生命周期方法。

该方法在 Using-Stateful-JS-Component 中有详细描述,re-frame但这我倾向于使用 D3 的方式:

(defn graph-render [graph-attrs graph-data]
  ;; return hiccup for the graph here
  (let [width (:width graph-attrs)
        height (:height graph-attrs)]
    [:svg {:width width :height height}
     [:g.graph]]))

(defn graph-component [graph-attrs graph-data]
  (r/create-class
   {:display-name "graph"
    :reagent-render graph-render
    :component-did-update (fn [this]
                            (let [[_ graph-attrs graph-data] (r/argv this)]
                              (update! graph-attrs graph-data)))
    :component-did-mount (fn [this]
                           (let [[_ graph-attrs graph-data] (r/argv this)]
                             (init! graph-attrs graph-data)))}))

(defn container []
  [:div {:id "graph-container"}
   [graph-component
    @graph-attrs-ratom
    @graph-data-ratom]])

保持外部/内部组合很重要,因为否则 React 不会正确填充它的 props。

需要注意的另一件事是reagent/argv向量的返回,如您所见,它包含第一项之后的道具。(reagent/props comp)在上面的 wiki 页面中看到过,但我自己从未尝试过。

于 2018-07-31T21:25:27.147 回答