clojure - Om 下一个教程 : Correctly calling the get-people function

标签 clojure clojurescript om

我目前正在关注 om-next tutorial .在 Adding Reads部分,有一个功能 get-people被定义为。与此功能一起,init-data定义了包含人员列表的 map 。

(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 。我不太明白我应该如何调用这个函数。有人可以帮我吗?谢谢!

最佳答案

好吧,我想通了。
init-data不是调用 get-people 的正确数据结构和。初始数据必须首先使用 Om 的 reconciler“核对”。 .您可以在本教程的 Normalization 中找到有关协调器的更多信息。部分。

调和init-data map 然后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}}}

这是对 get-people 的有效调用使用协调的 init-data 的函数:
; 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 关联的值。 key 。在这种情况下,该值是映射到 map 中的路径向量(每条路径本身就是一个向量)。
  • 接下来,映射路径并在每个向量上调用匿名函数。其中一个调用看起来像 (get-in st [:person/by-name "John"])并返回 {:name "John", :points 0} .
  • 将结果作为向量返回

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

    关于clojure - Om 下一个教程 : Correctly calling the get-people function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33491017/

    相关文章:

    reactjs - Reagent 生成一个传递 React.isValidClass(component) 的 React 组件?

    clojurescript - 调用 ".done"JS回调

    clojure - Re-frame 中的 reg-event-db、reg-event-fx 和 reg-event-ctx 有什么区别?

    clojurescript - 无法在渲染阶段之外操作光标

    unit-testing - 如何测试 midje 抛出的异常

    data-structures - Clojure 中 2D 游戏板的适当表示

    javascript - clojure/ClojureScript 中的 stringify/parse edn

    clojure - 如何配置 Leiningen 以使用企业存储库?

    clojurescript - OM 组件与普通函数

    clojurescript - 如何在 Om Clojurescript 中创建 Material UI 组件?