使用svelte-routing调用navigate('/')跳转后页面未刷新如何解决
问题原因
svelte-routing 提供的 navigate 方法依赖 Svelte 的组件响应式上下文才能触发 Router 组件重新渲染匹配路由。你在普通 .js 文件中调用 navigate 时,调用上下文不属于任何 Svelte 组件,Router 收不到路由变更的通知,因此只会更新地址栏,不会触发页面组件的重渲染。
可行解决方案
方案1:将navigate作为参数传入工具函数
在调用 checkLoggedIn 的 Svelte 组件中引入 navigate,作为参数传入函数,确保调用上下文正确:
// 调用checkLoggedIn的组件内代码 import { onMount } from 'svelte'; import { navigate } from 'svelte-routing'; import { checkLoggedIn } from './routeHandling.js'; onMount(() => { // 把组件上下文中的navigate传入 checkLoggedIn(navigate); })
调整routeHandling.js的函数定义:
import * as axios from "axios"; // 接收传入的navigate方法 export function checkLoggedIn(navigate) { console.log("checkLoggedIn is now getting executed"); if (window.location.pathname !== "/" && window.location.pathname !== "/registration") { axios.default.get('http://127.0.0.1:5000/user', { headers: { 'Authorization': `${localStorage.getItem("token")}` } }).catch(response => { navigate("/"); }); } }
方案2:通过全局store中转导航指令
如果需要在多处非组件场景触发导航,可以用Svelte store做状态中转:
- 新建全局store文件
src/stores/route.js
import { writable } from 'svelte/store'; export const targetRoute = writable(null);
- 调整
routeHandling.js代码
import { targetRoute } from './stores/route.js'; import * as axios from "axios"; export function checkLoggedIn() { console.log("checkLoggedIn is now getting executed"); if (window.location.pathname !== "/" && window.location.pathname !== "/registration") { axios.default.get('http://127.0.0.1:5000/user', { headers: { 'Authorization': `${localStorage.getItem("token")}` } }).catch(response => { // 写入要跳转的路径到store targetRoute.set("/"); }); } }
- 在应用根组件(定义Router的组件)中监听store变化,执行导航
<script> import { Router, Route, navigate } from 'svelte-routing'; import { targetRoute } from './stores/route.js'; // 响应式监听跳转目标 $: if ($targetRoute) { navigate($targetRoute); // 跳转后清空状态 targetRoute.set(null); } </script> <Router> <!-- 你的路由定义 --> </Router>
额外排查点
确认你的整个应用只有一个顶级Router实例,多实例场景下也会出现导航不生效的问题。
内容的提问来源于stack exchange,提问作者aa.hari.csbe
相关产品推荐
相关产品推荐

