代码之家  ›  专栏  ›  技术社区  ›  jmargolisvt

如何更新原子中的试剂向量

  •  2
  • jmargolisvt  · 技术社区  · 7 年前

    我有一个试剂原子:

    (defonce order (r/atom {:firstName "" :lastName "" :toppings [] }))
    

    我想把配料添加到 :toppings 矢量。我尝试了许多变体:

    (swap! (:toppings order) conj "Pepperoni") 这给了我: Uncaught Error: No protocol method ISwap.-swap! defined for type null:

    (swap! order :toppings "Pepperoni") 可以,但只是更新顺序,而不是 :浇头 矢量。当我放弃时 order ,我只得到最新的值。

    :浇头 矢量?

    3 回复  |  直到 7 年前
        1
  •  6
  •   grandinero    7 年前

    再解释一下,当你这么做的时候 (swap! (:toppings order) ...) ,您正在检索 :toppings 密钥来自 order ,如果它是一个地图,这是有意义的,但它是一个原子,所以 (:toppings order) 退货 nil .

    第一个参数 swap! 应该始终是原子( Reagent 原子以同样的方式工作)。第二个参数应该是一个函数,它将原子的内容作为第一个参数。然后,您可以选择提供更多参数,这些参数将传递给函数参数。

    您可以执行以下操作,而不是minhtuannguyen的回答:

    (swap! order
      (fn a [m]
        (update m :toppings
          (fn b [t]
            (conj t "Pepperoni")))))
    

    fn a 接收原子内部的映射,将其绑定到 m ,然后更新它并返回一个新映射,该映射成为原子的新值。

    如果你想,你可以重新定义 fn a 第二个论点:

    (swap! order
      (fn a [m the-key]
        (update m the-key
          (fn b [t]
            (conj t "Pepperoni"))))
      :toppings)
    

    现在作为第二个参数传递给 fn a ,然后传递给 update fn a . 我们可以对第三个参数做同样的处理 :

    (swap! order
      (fn a [m the-key the-fn]
        (update m the-key the-fn))
      :toppings
      (fn b [t]
        (conj t "Pepperoni")))
    

    使现代化 签名与相同 fn a fn a 完全我们可以简单地提供 使现代化 fn a :

    (swap! order update :toppings
      (fn b [t]
        (conj t "Pepperoni")))
    

    使现代化 fn b 另一个论点是:

    (swap! order update :toppings
      (fn b [t the-topping]
        (conj t the-topping))
      "Pepperoni"))
    

    再一次 conj 签名与相同 fn b 所以 fn b conj公司 取而代之的是:

    (swap! order update :toppings conj "Pepperoni")
    

    因此,我们最终得到了闵的答案。

        2
  •  5
  •   user2609980    7 年前

    我会转身 toppings 成一组。我认为你不想在系列中重复浇头,所以一套是合适的:

    (defonce order (r/atom {:first-name "" :last-name "" :toppings #{}})) ; #{} instead of []
    

    然后你仍然可以 conj 如另一个答复所述:

    (swap! order update :toppings conj "Pepperoni")
    

    但你也可以 disj :

    (swap! order update :toppings disj "Pepperoni")
    
        3
  •  4
  •   Minh Tuan Nguyen    7 年前

    (swap! order update :toppings conj "Pepperoni")