2015-11-03 21 views
4

我目前正沿着om-next tutorial。在Adding Reads部分中,定義了一個函數get-people。隨着此功能,init-data地圖被定義爲包含人員列表。Om Next教程:正確調用get-people功能

(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秒的載體。我不太明白我應該怎樣稱呼這個功能。有人能幫我嗎?謝謝!

回答

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-數據到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. Fi首先,該函數檢索與:list/one鍵相關的值。在這種情況下,該值是到地圖中的路徑矢量(每個路徑本身就是一個矢量)。
  2. 接下來,映射路徑並調用每個向量上的匿名函數。其中一個呼叫看起來像(get-in st [:person/by-name "John"]),並返回{:name "John", :points 0}
  3. 返回的結果作爲載體

若有人讀這篇文章,希望進一步澄清,請讓我知道。