我目前正在关注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的向量。我不太明白该如何调用这个函数。有人能帮帮我吗?谢谢!
发布于 2015-11-03 12:30:57
好吧,我想通了。
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键关联的值。在本例中,该值是映射的路径向量(每个路径本身都是路径上的vector).(get-in st [:person/by-name "John"]),并以向量的形式返回{:name "John", :points 0}.
如果有人正在阅读这篇文章,并想进一步澄清,请让我知道。
https://stackoverflow.com/questions/33491017
复制相似问题