ClojureScript。重新渲染时重置 Reagent 中的原子

标签 clojurescript reagent re-frame

我正在显示一组测验问题,并且为每个问题分配一个编号,以便在浏览器中显示它们时对其进行编号:

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

相关文章:

clojurescript - 这个语法 (.-body ...) 在 clojurescript/reagent 中是什么意思?

clojurescript - Clojurescript Om 中的应用程序状态和组件本地状态有什么区别?

clojure - 如何从重新构建的事件中调度事件

clojure - 为什么在此 ClojureScript 片段中使用 ^ 字符?

javascript - (node/enable-util-print!) 是做什么的?

phantomjs - 如何编译代码 ClojureScript 以在 PhantomJS 中使用?

clojurescript - 如何使用试剂动态更改 CSS 类名?

clojure - 使用 reagent 和 re-frame 时,如何在 crud 类型的应用程序中实现撤消和重做?

semantic-ui - Clojurescript Semantic UI React Search 自定义渲染器