ClojureScript/Reagent用于函数不起作用

4
我最近在我的Clojurescript项目中使用reagent和re-frame,但遇到了一个问题:我有HTML自定义标签。
<question id="1"></question>
<question id="2"></question>

我想使用cljs函数将它们与我的reagent生成的html进行交换。
(defn mypanel []
 [:p "Hi!"])

(let [q (.getElementsByTagName js/document "question")]
  (for [i (range 2)]
    ^{:keys i}
    (reagent/render [mypanel]
                  (aget (.getElementsByTagName js/document "question") i))))

但它不起作用,我尝试了在不使用for函数的情况下进行测试
(reagent/render [mypanel]
     (aget (.getElementsByTagName js/document "question") 0))

只使用一个标签时,一切都正常。

我不知道为什么使用for函数时无法工作,或者reagent不能以这种方式工作?有人有建议吗?

我对此非常菜鸟。

2个回答

7

for 生成一个惰性序列,也就是说,在需要求值之前不会执行任何工作。你无法使用惰性序列来强制副作用,因为它们永远不会被计算(render 就是这样的例子)。如果要强制副作用,你应该用 doseq 代替它。在你的情况下,可能更适合使用 dotimes

(let [q (.getElementsByTagName js/document "question")]
  (dotimes [i 2]
    ^{:keys i}
    (reagent/render [mypanel]
                  (aget (.getElementsByTagName js/document "question") i))))

1
成功了!我明白了,渲染有副作用!非常感谢! - Nyoman Arie Pranasakti

0
另一个选择可能是强制使用由for返回的lazyseq:
 (doall (for [i (range 2)]....  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接