【问题标题】:Getting error Uncaught Error: Assert failed: Reaction is read only; on-set is not allowed获取错误未捕获错误:断言失败:反应是只读的;现场不允许
【发布时间】:2018-06-04 10:56:15
【问题描述】:

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

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

下面的函数预计会生成一个对应于app的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
   ))

【问题讨论】:

  • :on-change 匿名函数周围有额外的括号吗?
  • @exupero 这是一个错字。我已经纠正了。但是,错误仍然存​​在。
  • 您能否展示一下处理您的db 的代码部分?你是怎么储存的?

标签: clojure single-page-application clojurescript reagent re-frame


【解决方案1】:

根据您问题的标签,我推测您正在使用 re-frame。

can't update the database in re-frame directly。相反,您应该注册一个更新数据库的事件处理程序,如下所示(具体代码取决于您的数据库结构):

;; (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])
...

【讨论】:

  • 感谢 Aleph :)。但是,我现在遇到了一个新错误:No protocol method IDeref.-deref defined for type cljs.core/PersistentVector: [{:checked false, :text "Sample text"} {:checked false, :text "Sample text" } {:checked true, :text "Sample text"}] 我已经按照您的建议使用初始化数据库的部分代码更新了 sn-p。
  • 您应该确保您没有取消引用您的数据库订阅两次。如果gen-checkboxdb参数已经包含取消引用订阅,则不应在函数体中添加@... :label (:text (get db index)) :model (:checked (get db index))
猜你喜欢
  • 1970-01-01
  • 2016-11-27
  • 2019-04-16
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2012-11-28
相关资源
最近更新 更多