简体   繁体   English

为什么无法在Let中定义试剂成分的状态?

[英]Why is it not possible to define the state of a reagent component in a let?

Say that we have a text text area defined in hiccup syntax. 假设我们有一个打ic语法定义的文本文本区域。

(def written-text (reagent/atom ""))

(defn text-area []
    [:textarea
     {:value     @written-text
      :on-change #(reset! written-text (-> % .-target .-value))
      :on-click  #(println @written-text)}])

Say that we want to have multiple copies of text-area in our document, each with different state in them. 假设我们要在文档中拥有多个文本区域副本,每个副本区域中的状态都不同。 Then we'll have to move the state currently available to all in the current namespace into a lexically scoped symbol. 然后,我们必须将当前可用于当前名称空间的所有人的状态移动到词法范围的符号中。 Something like: 就像是:

(defn text-area []
  (let [written-text (reagent/atom "")]
    [:textarea
     {:value     @written-text
      :on-change #(reset! written-text (-> % .-target .-value))
      :on-click  #(println @written-text)}]))

But as it stands this code doesn't work. 但就目前而言,此代码不起作用。 The text field always ends up empty no matter what the user inputs. 无论用户输入什么,文本字段始终以空结尾。 Why is that? 这是为什么? And how do I enclose my state in a per component lexical scope? 以及如何将我的状态包含在每个组件的词法范围内?

The answer to this issue can be found in the re-frame documentation which describes the different forms of components that are normally found in a reagent project. 该问题的答案可在重组文档中找到,该文档描述了通常在试剂项目中发现的不同形式的组件。 It states that in order to provide a persistent lexical scope for the per-component state to live in, one must write a function which returns another rendering function; 它指出,为了为每个组件的状态提供持久的词法作用域,必须编写一个函数,该函数返回另一个渲染函数。 else the state atom will be redefined every time reagent tries to re-render the component. 否则,每次试剂尝试重新渲染组件时,状态原子都会被重新定义。 So for the given component: 因此,对于给定的组件:

(defn text-area []
  (let [written-text (atom "")]
    (fn []                                       
      [:textarea
        {:value     @written-text
         :on-change #(reset! written-text (-> % .-target .-value))}])))

This way, the function called by reagent when it wishes to redraw the component is the internal, anonymous, function. 这样,当试剂希望重绘组件时调用的函数就是内部匿名函数。 The let which defines the lexical scope won't be re-run. 定义词汇范围的let将不会重新运行。

All credit for this answer goes to user mccraigmccraig on the clojurians slack. 该答案的全部功劳归于clojurians闲暇时的用户mccraigmccraig。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM