如何在原子状态下更新向量中的元素

How to update an element in vector in atom state

我正在尝试使用 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))}]])

我在这里传递更新的待办事项,但传递始终为真是不正确的。可能传递它的索引就足够了,它会解决我的问题,但我不知道该怎么做。

要切换 :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 的地图的对应关系。

(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)}]])