我是Clojure和Reagent的新手。请告诉我如何在atom变量contacts中首先打印变量?
(def app-state (R /原子 {:contacts [{:first" Ben" :最后" Lem" :中" Ab"}]}))
答案 0 :(得分:2)
以下是使用Clojure (get-in m ks)函数访问您正在寻找的值的简明方法:
(get-in @app-state [:contacts 0 :first])
答案 1 :(得分:1)
首先: reagent tutorial是一个非常好的起点。它甚至为您提供了解决此问题的示例。
由于试剂atom
可以作为常规Clojurescript原子处理,因此您可以使用所有正常的序列操作。请记住,为了访问当前值,您必须通过@
取消引用原子。如果您真的只想访问原子中的第一个: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 tutorial。
答案 2 :(得分:0)
@app-state
将为您提供r / atom内的任何内容,(:first (first (:contacts @app-state)))
将返回第一个元素,(println (:first (first (:contacts @app-state))))
将输出打印到浏览器控制台(因此您需要让开发人员工具控制台打开看看。)
请注意,要将println
输出到浏览器开发人员工具控制台,您需要在代码中包含以下内容:
(enable-console-print!)
答案 3 :(得分:0)
作为额外的,您可能会看到这通常写为
(->> @app-state
:contacts
(mapv :first)
first
了解这里发生的事情很有用。
->>
是一个名为thread-last的宏,它会将上面的代码重写为
(first (mapv :first (:contacts @app-state)))
线程最后有点奇怪但是当很多事情发生时它使代码更具可读性。我建议在其他评论中提到的试剂教程之上阅读this。