我正在显示一组测验问题,并且为每个问题分配一个编号,以便在浏览器中显示它们时对其进行编号:
(defn questions-list
[]
(let [counter (atom 0)]
(fn []
(into [:section]
(for [question @(re-frame/subscribe [:questions])]
[display-question (assoc question :counter (swap! counter inc))])))))
问题是,当有人在浏览器中编辑问题时(调用调度并更新“app-db”映射),组件会重新渲染,但原子“计数器”逻辑上从最后一个数字开始不是从零开始。所以我需要重置原子但我不知道在哪里。我尝试在匿名函数内使用 let 但没有成功。
最佳答案
在这种情况下,我只需完全删除状态。我还没有测试过这段代码,但你的想法势在必行。您尝试做的事情的功能版本是这样的: 贫穷但无国籍:
(let [numbers (range 0 (count questions))
indexed (map #(assoc (nth questions %) :index %) questions)]
[:section
(for [question indexed]
[display-question question])])
但这很丑陋,而且 nth 效率低下。那么让我们尝试一个更好的。事实证明,map 可以采用多个集合作为其参数。
(let [numbers (range 0 (count questions))
indexed (map (fn [idx question] (assoc question :index idx)) questions)]
[:section
(for [question indexed]
[display-question question])])
但更好的是,事实证明有一个内置函数正是用于此目的。我实际上会写什么:
[:section
(doall
(map-indexed
(fn [idx question]
[display-question (assoc question :index idx)])
questions))]
注意:这些代码实际上都没有运行过,因此您可能需要在运行之前对其进行一些调整。我建议查找 ClojureDocs 中的所有函数确保您了解他们的工作。
关于ClojureScript。重新渲染时重置 Reagent 中的原子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537884/