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

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

  •  0
  • soeik  · 技术社区  · 7 年前

    我试图用ClojureScript和试剂框架创建一种待办事项列表。我将应用程序状态定义为atom:

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

    和功能切换todo:

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

    这里我传递更新的todo,但传递始终为true是不正确的。也许通过它的索引就足够了,它将解决我的问题,但我不知道如何做到这一点。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Caleb Macdonald Black    7 年前
    (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)}]])
    
        2
  •  0
  •   Alan Thompson    7 年前

    切换 :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 里面。