我目前正在跟随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的向量。我不太明白应该怎么称呼这个功能。有人可以帮帮我吗?谢谢!
答案 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}]
以下是发生的事情:
:list/one
键关联的值。在这种情况下,该值是映射到映射的路径的向量(每个路径本身就是一个向量)。(get-in st [:person/by-name "John"])
并返回{:name "John", :points 0}
。如果有人正在阅读此内容并希望进一步澄清,请告知我们。