我们将 Chart.js 与 clojurescript 和 Reagent 一起使用。现在我知道 Chart.js 有一个 Chart.update() 方法来用新数据更新图表。所以问题是,如何设置我的组件,以便它在 :reagent-render 上渲染图表,但可能得到 :component-will-update 来调用 Chart.update() 方法?
基本上,有没有办法获取从 :component-will-update 函数中的 :reagent-render 函数创建的图表的句柄?
最佳答案
在这种情况下,您遵循的通常模式是将有状态/可变对象包装在 React 组件中并使用 React 的生命周期方法。
re-frame
的 Using-Stateful-JS-Component 详细描述了该方法。但这就是我在 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
向量的返回,正如您所看到的,它包含第一个项目之后的 Prop 。我在上面的 wiki 页面中看到过(reagent/props comp)
,但我自己从未尝试过。
关于chart.js - Clojurescript/Reagent/Chart.js - 试剂生命周期 - Chart.update(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47230863/