页面加载时未触发defroute

时间:2019-04-28 06:42:15

标签: clojurescript re-frame secretary

我在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-panel中的events.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在网页加载以及网站导航时触发?

2 个答案:

答案 0 :(得分:0)

基于可用代码的一些猜测:

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

答案 1 :(得分:0)

我怀疑您已成为重组框架“陷阱”的受害者,该框架中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"))