【问题标题】:How to access clojure reagent atom map variable?如何访问 clojure 试剂原子图变量?
【发布时间】:2016-01-26 11:06:02
【问题描述】:

我是 Clojure 和 Reagent 的新手。请告诉如何在原子变量联系人中首先打印变量?

(def 应用程序状态 (r/原子 {:contacts [{:first "Ben" :last "Lem" :middle "Ab"}]}))

【问题讨论】:

    标签: clojure clojurescript reagent


    【解决方案1】:

    首先reagent tutorial 是一个非常好的起点。它甚至为您提供了解决此问题的示例。

    由于试剂atom 可以被视为常规 Clojurescript 原子,因此您可以使用所有正常的序列操作。请记住,为了访问当前值,您必须通过 @ 取消引用 atom。如果您真的只想访问 atom 中的第一个 :first

    (:first (first (:contacts @app-state)))(get (first (get @app-state :contacts)) :first)

    或者,如果您认为它更具可读性

    (-> @app-state
        :contacts
        first
        :first)
    

    我想您可能想要做的是定义一些函数以使访问更容易,例如:

    (defn get-contacts!
      "Returns the current vector of contacts stored in the app-state."
      []
      (:contacts @app-state))
    
    (defn get-first-names!
      "Return a vector of all first names in the current list of contacts in the
       app-state."
      []
      (mapv :first (get-contacts!)))
    

    请记住,在 reagent 中(实际上是一般情况下)您可能希望尽可能少地取消引用该原子,因此请寻找一个取消引用它的好地方并只使用常规函数对简单序列而不是原子进行操作。

    不过,我真的建议你去阅读前面提到的reagent tutorial

    【讨论】:

      【解决方案2】:

      这是使用 Clojure 的 (get-in m ks) 函数访问您正在寻找的值的简洁方法:

      (get-in @app-state [:contacts 0 :first])
      

      【讨论】:

        【解决方案3】:

        作为一个额外的,你可能会看到这通常写成

        (->> @app-state
             :contacts
             (mapv :first)
             first
        

        了解这里发生的事情很有用。

        ->> 是一个名为 thread-last 的宏,它将把上面的代码重写为

        (first (mapv :first (:contacts @app-state)))
        

        Thread last 一开始有点奇怪,但是当很多事情发生时,它使代码更具可读性。我建议您在其他 cmets 中提到的试剂教程之上,阅读this

        【讨论】:

          【解决方案4】:

          @app-state 将为您提供 r/atom 中的任何内容,(:first (first (:contacts @app-state))) 将返回第一个元素,(println (:first (first (:contacts @app-state)))) 会将输出打印到浏览器控制台(因此您需要打开开发人员工具控制台才能看到它)。

          请注意,要让println 输出到浏览器开发人员工具控制台,您需要在代码中包含此行:

          (enable-console-print!)
          

          【讨论】:

            猜你喜欢
            • 2017-03-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-04-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多