defroute没有在页面加载时触发

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

我在routes.cljs的根目录中的src/cljs/project/routes.cljs文件中定义了应用程序路由。

(defn app-routes []
  (secretary/set-config! :prefix "#")

  (defroute
    "/" []
    (re-frame/dispatch [::events/set-active-panel :welcome-panel])))
  ; shortened for brevity

它在core.cljs初始化

; required [portfolio-app.events :as events]
(defn ^:export init []
  (routes/app-routes)
  (re-frame/dispatch-sync [::events/initialize-db])
  (dev-setup)
  (mount-root))

它被派遣到::events/set-active-panelevents.cljs

(re-frame/reg-event-db
 ::set-active-panel
 (fn-traced [db [_ active-panel]]
   (assoc db :active-panel active-panel)))

并且在:active-panel订阅了subs.cljs

(re-frame/reg-sub
 ::active-panel
 (fn [db _]
   (:active-panel db)))

我在:active-panel订阅了layout.cljs

; required [portfolio-app.subs :as subs]
(defn panel []
  (let [active-panel (re-frame/subscribe [::subs/active-panel])]
    [:div
     "which panel? " @active-panel]))

当我第一次访问页面时,@active-panelnil。仅当我浏览页面时才会调度该面板。我知道这最初有效。我在提交中看不到可能破坏它的任何内容。

如何让我的defroutes在页面加载和网站导航时触发?

clojurescript re-frame secretary
2个回答
0
投票

几个猜测基于可用的代码:

  • 您是在页面加载时调用secretary/dispatch还是仅在后续导航中调用?
  • ::events/initialize-db设置正确后,你的:active-panel是否正在初始化数据库,导致你的订阅返回nil

0
投票

我怀疑你已经成为重新框架“gotcha”的受害者,因为它没有以events形式列出,因此在编译过程中省略了像(:require ...)这样的命名空间。有关详细信息,请参阅the Gotcha documentation

为了使(:require ...)更明确,更难以忘记,我总是将所有(reg-event-* ...)调用包装在一个从主程序初始化的更大的函数中:

(ns demo.core  
  (:require 
     [demo.events :as events]
     [demo.subs :as subs]
     ...))

(defn app-start
  "Initiates the cljs application"
  []
  (events/define-all-events!)
  (subs/initialize-all)
  (configure-browser-routing!)
  ...)

然后:

(ns demo.events ...)
(defn define-all-events! []
  (reg-event-db ...)
  (reg-event-fx ...)
  ...)

我使用类似的“功能包装”技术进行秘书/会计路由,也用于定义订阅(即reg-sub)。例如:

(defn configure-browser-routing! []
  (println "configure-browser-routing - enter")

  (secretary/defroute "/all" []
    (println :secretary-route-all)
    (browser-nav-handler :all))
  (secretary/defroute "/active" []
    (println :secretary-route-active)
    (browser-nav-handler :active))
  (secretary/defroute "/completed" []
    (println :secretary-route-completed)
    (browser-nav-handler :completed))
  (secretary/defroute "/*" []
    (println ":secretary-route-all  *** default ***")
    (browser-nav-handler :all))

  (accountant/configure-navigation!
    {:nav-handler  (fn [path]
                     (t/spy :accountant--nav-handler--path path)
                     (secretary/dispatch! path))
     :path-exists? (fn [path]
                     (t/spy :accountant--path-exists?--path path)
                     (t/spy :accountant--path-exists?--result
                       (secretary/locate-route path)))})
  (println "configure-browser-routing - leave"))
© www.soinside.com 2019 - 2024. All rights reserved.