You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Clojure与ClojureScript搭建带路由的SPA应用

排查步骤与解决方案

你遇到的「No view specified for route」报错是路由配置缺失导致的,该功能完全不需要websockets支持,你需要补全以下几个环节的配置即可:

1. 补全路由依赖与基础定义

《Web Development with Clojure(第三版)》默认使用reitit作为前端路由库,首先确认你已在项目依赖中引入reitit,然后在core.cljs的命名空间引用里添加路由相关引用:

(ns my-spa.core
  (:require
   [reagent.core :as r]
   [reagent.dom :as dom]
   [re-frame.core :as rf]
   [mount.core :as mount]
   ;; 新增路由依赖
   [reitit.frontend :as rtf]
   [reitit.frontend.easy :as rtfe]))

接着定义路由表,把路径和对应的页面组件绑定:

(def routes
  [["/" {:name :home
         :view home}]
   ["/about" {:name :about
              :view about-page}]])

2. 实现路由对应的re-frame逻辑

你用到的[:router/current-route]订阅还没有注册,需要补全对应的订阅和事件处理:

;; 注册路由查询订阅
(rf/reg-sub
 :router/current-route
 (fn [db _]
   (:current-route db)))

;; 注册路由变更事件,把匹配到的路由存入re-frame db
(rf/reg-event-db
 :router/navigated
 (fn [db [_ new-match]]
   (assoc db :current-route new-match)))

3. 初始化路由并修改导航跳转逻辑

首先修改init!函数,启动路由监听:

(defn init! []
  (.log js/console "Initializing App...")
  (mount/start)
  ;; 新增路由启动逻辑
  (rtfe/start! routes
               (fn [new-match]
                 (rf/dispatch [:router/navigated new-match]))
               {:use-fragment false})
  (rf/dispatch [:app/initialize])
  (mount-components))

然后修改导航栏的a标签,避免原生跳转触发整页刷新:

[:div.navbar-start
 [:a.navbar-item
  {:on-click #(rtfe/push-state :home)}
  "Home"]
 [:a.navbar-item
  {:on-click #(rtfe/push-state :about)}
  "About"]]

可选兜底配置

如果还是匹配失败,可以在路由表最后添加通配符兜底路由,方便排查问题:

["/*path" {:name :not-found
           :view (fn [] [:div "页面不存在"])}]

内容的提问来源于stack exchange,提问作者JasonXuNAlasfjdao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:39:03