【问题标题】:Why need to return a function in Reagent component?为什么需要在 Reagent 组件中返回一个函数?
【发布时间】:2021-01-03 09:33:18
【问题描述】:

来自Reagent introduction,一个简单的定时器组件:

(defn timer-component []
  (let [seconds-elapsed (r/atom 0)]
    (fn []
      (js/setTimeout #(swap! seconds-elapsed inc) 1000)
      [:div
       "Seconds Elapsed: " @seconds-elapsed])))

下面写着

前面的例子还用到了 Reagent 的另一个特性:一个组件 函数可以返回另一个函数,用于执行实际的 渲染。使用与 第一个。

这允许您对新创建的组件进行一些设置 无需诉诸 React 的生命周期事件。

有人可以提醒我这里的基本原理吗?为什么我们需要这个匿名函数?为什么不只是

(defn timer-component []
  (let [seconds-elapsed (r/atom 0)]
    (js/setTimeout #(swap! seconds-elapsed inc) 1000)
    [:div
     "Seconds Elapsed: " @seconds-elapsed])))

【问题讨论】:

    标签: clojurescript reagent


    【解决方案1】:

    据我所知,Reagent 每次想要渲染时都会调用 timer-component - 可能会一遍又一遍地设置相同的状态 (seconds-elapsed)。

    通过返回该匿名函数,它告诉 Reagent“使用它来渲染 timer-component”。通过这种方式,您的状态设置与渲染分离,就像您的 doco 引用所说的那样,它是一种不使用 Reacts 生命周期事件来执行状态设置的方法。

    希望这是有道理的

    【讨论】:

      【解决方案2】:

      Tl;dr:返回的匿名函数是render 方法,每个组件都必须有。如果您在 Reagent 中使用with-let macro,则可以省略匿名函数。

      React 组件不可或缺的部分是render function,它接受单个对象参数并返回一个 React 元素。 render的区别 并且组件构造函数是,虽然这两种方法都在构造时调用,renderis called on each update。 (比如有人调用了组件的setState方法)。

      在上面的例子中,内部匿名函数和外部timer-component 函数之间的区别与render 和构造函数之间的区别相同。请注意,匿名函数closes over 绑定在let 子句中的变量,这允许它是有状态的。如果timer-component 本身就是render 函数,那么它会在每次更新时被调用,而seconds-elapsed 将被无限重置为零。

      请参阅 Reagent repo 上名为“Creating Reagent Components”的文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 2018-06-04
        相关资源
        最近更新 更多