- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个试剂原子:
(defonce order (r/atom {:firstName "" :lastName "" :toppings [] }))
我想在 :toppings
向量中添加浇头。我尝试了很多变体:
(swap! (:toppings order) conj "Pepperoni")
这给了我: Uncaught Error: No protocol method ISwap.-swap!为 null 类型定义:
(swap! order :toppings "Pepperoni")
有点效果,但只是更新顺序,而不是 :toppings
向量。当我取消引用 order
时,我只得到最新的值。
向我的 :toppings
向量添加(和删除)值的正确方法是什么?
最佳答案
再解释一下,当你执行 (swap! (:toppings order) ...)
时,你正在从 中检索
,如果它是一个 map 就有意义,但它是一个原子,所以 :toppings
键>order(:toppings order)
返回 nil
。
swap!
的第一个参数应该始终是一个原子(Reagent
原子的工作方式相同)。第二个参数应该是一个函数,它将原子的内容作为它的第一个参数。然后,您可以选择提供更多参数,这些参数将传递给函数参数。
您可以执行以下操作,而不是 minhtuannguyen 的回答:
(swap! order
(fn a [m]
(update m :toppings
(fn b [t]
(conj t "Pepperoni")))))
fn a
接收 atom 内部的 map,将其绑定(bind)到 m
,然后更新它并返回一个新的 map,成为 atom 的新值。
如果您愿意,可以重新定义 fn a
以获取第二个参数:
(swap! order
(fn a [m the-key]
(update m the-key
(fn b [t]
(conj t "Pepperoni"))))
:toppings)
:toppings
现在作为第二个参数传递给 fn a
,然后传递给 fn a 内部的
。我们可以对 update
update
的第三个参数做同样的事情:
(swap! order
(fn a [m the-key the-fn]
(update m the-key the-fn))
:toppings
(fn b [t]
(conj t "Pepperoni")))
现在 update
与 fn a
具有相同的签名,因此我们不再需要 fn a
。我们可以简单地直接提供 update
来代替 fn a
:
(swap! order update :toppings
(fn b [t]
(conj t "Pepperoni")))
但我们可以继续,因为 update
还接受更多参数,然后将这些参数传递给提供给它的函数。我们可以重写 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")
因此,我们得到了 minhtuannguyen 的答案。
关于clojure - 如何更新原子中的试剂向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46454838/
我是一名优秀的程序员,十分优秀!