【问题标题】:Om Next Tutorial: Correctly calling the get-people functionOm Next Tutorial: 正确调用 get-people 函数
【发布时间】:2015-11-03 03:42:37
【问题描述】:

我目前正在关注 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]

如您所见,我只是返回了一个 nils 向量。我不太明白我应该如何调用这个函数。有人可以帮我吗?谢谢!

【问题讨论】:

    标签: clojure clojurescript om


    【解决方案1】:

    好吧,我想通了。

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

    协调 init-data 映射,然后 derefing 数据返回此规范化数据结构:

    {: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. 以向量形式返回结果

    如果有人正在阅读本文并希望进一步澄清,请告诉我。

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      相关资源
      最近更新 更多