我正在尝试使用ClojureScript和试剂框架创建一种待办事项列表。我将应用程序状态定义为原子:
(def app-state
(r/atom
{:count 3
:todolist
[{:id 0 :text "Start learning mindcontrol" :finished true}
{:id 1 :text "Read a book 'Debugging JS in IE11 without pain'" :finished false}
{:id 2 :text "Become invisible for a while" :finished false}]}))
具有更新待办事项列表的功能:
(defn update-todolist [f & args]
(apply swap! app-state update-in [:todolist] f args))
然后功能切换待办事项:
(defn toggle-todo [todo]
(update-todolist update-in [2] assoc :finished true))
现在我要直接通过其索引更新矢量元素。
我正在使用此功能渲染每个项目:
(defn item [todo]
^{:key (:id todo)}
[:div
[:span {:class "item-text"} (:text todo)]
[:i {:class (str "ti-check " (if (:finished todo) "checked" "unchecked"))
:on-click #(toggle-todo (assoc todo :finished true))}]])
在这里,我正在传递更新的待办事项,但始终传递true并不正确。也许只要传递它的索引就足够了,它将解决我的问题,但是我不知道该怎么做。
答案 0 :(得分:1)
(def app-state
(r/atom
{:count 3
:todolist
[{:id 0 :text "Start learning mindcontrol" :finished true}
{:id 1 :text "Read a book 'Debugging JS in IE11 without pain'" :finished false}
{:id 2 :text "Become invisible for a while" :finished false}]}))
(defn update-todolist [f & args]
(apply swap! app-state update-in [:todolist] f args))
(defn toggle-todo [todo]
(swap! app-state update-in [:todolist (:id todo) :finished] not))
(defn item [todo]
^{:key (:id todo)}
[:div
[:span {:class "item-text"} (:text todo)]
[:i {:class (str "ti-check " (if (:finished todo) "checked" "unchecked"))
:on-click #(toggle-todo todo)}]])
答案 1 :(得分:0)
要切换:finished
键的值,只需使用not
:
(swap! app-state update-in [:todolist 2 :finished] not) =>
{:count 3,
:todolist
[{:id 0, :text "Start learning mindcontrol",
:finished true}
{:id 1, :text "Read a book 'Debugging JS in IE11 without pain'",
:finished false}
{:id 2, :text "Become invisible for a while",
:finished true}]}
但是,这并不能告诉您索引2
与其中包含:id 2
的地图如何对应。