ClojureScript。发生重新渲染时,重置试剂中的原子

问题描述 投票:2回答:1

我正在显示一组用于测验的问题,并且为每个问题分配一个数字,以便在浏览器中显示它们时给它们编号:

(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”映射),该组件被重新渲染,但是原子“ counter”在逻辑上从最后一个数字开始而不是从零开始。所以我需要重置原子,但是我不知道在哪里。我尝试在匿名函数中使用let,但这没有用。

clojurescript reagent re-frame
1个回答
1
投票

在这种情况下,我将完全删除状态。我没有测试过这段代码,但是您必须在这里进行思考。您尝试执行的功能版本类似于以下内容:可怜但无状态:

(let [numbers (range 0 (count questions))
      indexed (map #(assoc (nth questions %) :index %) questions)]
  [:section
   (for [question indexed]
     [display-question question])])

但这很丑,第n个效率低下。因此,让我们尝试一个更好的选择。结果表明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中的所有功能,以确保您了解它们的作用。

© www.soinside.com 2019 - 2024. All rights reserved.