首页 > 解决方案 > 获取错误未捕获错误:断言失败:反应是只读的;现场不允许

问题描述

我是clojure和试剂的新手。我试图生成动态数量的复选框,其状态存储在应用程序状态中,这是一个像这样的字典列表

[{:checked false, :text "Sample text 1"} {:checked false, :text "Sample text 2"} {:checked false, :text "Sample text 3"}]

下面的函数预计会生成一个对应于应用程序db(db)的指定索引的复选框。该功能可以完成工作,并且复选框是可点击的。

(defn gen-checkbox [index db] 
     [re-com/checkbox
            :label (:text (@db index))
            :model (:checked (@db index))
            :on-change #(swap! db assoc-in [index :checked] (not(:checked (@db index))))
     ])

但是,当我单击任何复选框时,我会在浏览器控制台中收到此错误。

Uncaught Error: Assert failed: Reaction is read only; on-set is not allowed

错误发生在swap!。有人能指出我做错了什么吗?

db初始化部分如下:

(re-frame/reg-event-db ::initialize-db 
   (fn [_ _] 
      (atom [{:checked false :text "Sample text"}, {:checked false :text "Sample text"}, {:checked false :text "Sample text"}])
   ))

我还有一个功能来检索数据库。我目前正在

(re-frame/reg-sub ::getdb 
   (fn [db]
      @db
   ))

标签: clojuresingle-page-applicationclojurescriptreagentre-frame

解决方案


根据您问题的标签,我认为您正在使用重新框架。

不能直接更新 re-frame 中的数据库。相反,您应该注册一个更新数据库的事件处理程序,如下所示(确切的代码取决于您的数据库的结构):

;; (require '[re-frame.core :as rf])

(rf/reg-event-db
 :toggle-checkbox
 (fn [db [_ index]]
   (update-in db [index :checked] not)))

然后在复选框渲染器的代码中分派事件:

...
:on-change #(rf/dispatch [:toggle-checkbox index])
...

推荐阅读