Om Next教程:正确调用get-people功能

时间:2015-11-03 03:42:38

标签: clojure clojurescript om

我目前正在跟随om-next tutorial。在Adding Reads部分中,定义了一个函数get-people。除此功能外,还定义了init-data地图,其中包含人员列表。

(defn get-people [state key]
  (let [st @state]
    (into [] (map #(get-in st %)) (get st key))))

(def init-data {:list/one
 [{:name "John", :points 0}
  {:name "Mary", :points 0}
  {:name "Bob", :points 0}],
 :list/two
 [{:name "Mary", :points 0, :age 27}
  {:name "Gwen", :points 0} 
  {:name "Jeff", :points 0}]})

我尝试调用此功能。

(get-people (atom init-data) :list/one) ;; => [nil nil nil]

如您所见,我只是回到nil s的向量。我不太明白应该怎么称呼这个功能。有人可以帮帮我吗?谢谢!

1 个答案:

答案 0 :(得分:5)

好吧,我明白了。

init-data不是调用get-people的正确数据结构。首先必须使用Om reconciler“协调”初始数据。您可以在教程的Normalization部分找到有关协调程序的更多信息。

协调init-data地图然后deref数据会返回此规范化数据结构:

{:list/one
 [[:person/by-name "John"]
  [:person/by-name "Mary"]
  [:person/by-name "Bob"]],
 :list/two
 [[:person/by-name "Mary"]
  [:person/by-name "Gwen"]
  [:person/by-name "Jeff"]],
 :person/by-name
 {"John" {:name "John", :points 0},
  "Mary" {:name "Mary", :points 0, :age 27},
  "Bob" {:name "Bob", :points 0},
  "Gwen" {:name "Gwen", :points 0},
  "Jeff" {:name "Jeff", :points 0}}}

以下是使用已协调的init-data对get-people函数的有效调用:

; reconciled initial data
(def reconciled-data
  {:list/one
   [[:person/by-name "John"]
    [:person/by-name "Mary"]
    [:person/by-name "Bob"]],
   :list/two
   [[:person/by-name "Mary"]
    [:person/by-name "Gwen"]
    [:person/by-name "Jeff"]],
   :person/by-name
   {"John" {:name "John", :points 0},
    "Mary" {:name "Mary", :points 0, :age 27},
    "Bob" {:name "Bob", :points 0},
    "Gwen" {:name "Gwen", :points 0},
    "Jeff" {:name "Jeff", :points 0}}}

; correct function call
(get-people (atom reconciled-data) :list/one)

; returned results
[{:name "John", :points 0}
 {:name "Mary", :points 0, :age 27}
 {:name "Bob", :points 0}]

以下是发生的事情:

  1. 首先,该函数检索与:list/one键关联的值。在这种情况下,该值是映射到映射的路径的向量(每个路径本身就是一个向量)。
  2. 接下来,映射路径并在每个向量上调用匿名函数。其中一个调用看起来像(get-in st [:person/by-name "John"])并返回{:name "John", :points 0}
  3. 将结果作为向量返回
  4. 如果有人正在阅读此内容并希望进一步澄清,请告知我们。