【问题标题】:Why does a component not render correctly in Reagent?为什么组件无法在 Reagent 中正确呈现?
【发布时间】:2017-08-03 14:51:09
【问题描述】:

在使用 Clojurescript 阅读 Reagent 上的 this post 时,我尝试了不同的方法来实现 timer-component 组件。然而,我的第一次尝试没有奏效:

(defn timer-component []
  (fn []
    (let [seconds-elapsed (r/atom 0)]
      (js/setTimeout #(swap! seconds-elapsed inc) 1000)
      [:p (str "Expired time: " @seconds-elapsed)])))

正如调试日志语句所显示的,计时器仍会定期调用,seconds-elapsed 变量仍会正确更新。但是,显示不会更新,组件始终显示“过期时间:0”。

与博文中的代码示例相比,我的组件交换了fn 和let 声明,这种修改似乎阻止了正确显示,但没有正确更新组件。我的期望是要么组件更新并正确显示,要么既不更新也不显示。

我的问题是为什么会这样?这是 Reagent 中的错误还是我滥用 API?

【问题讨论】:

    标签: clojurescript reagent


    【解决方案1】:

    您总是看到相同的值,因为每次(重新)渲染都会调用内部匿名函数。因此,seconds-elapsed 被一次又一次地绑定到值为 0 的新原子。这不是错误,而是 Reagent 应该如何工作。

    您的组件是“Form-2”,应在外部函数timer-component 中声明其本地状态,每个组件仅调用一次。 Re-frame documentation explains different forms of Reagent components很好。

    Re-frame docs 将 cmets 添加到 Reagent 教程中的示例中,这可能有助于澄清:

    (defn timer-component []
      (let [seconds-elapsed (reagent/atom 0)]     ;; setup, and local state
        (fn []        ;; inner, render function is returned
          (js/setTimeout #(swap! seconds-elapsed inc) 1000)
          [:div "Seconds Elapsed: " @seconds-elapsed])))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多