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

SolidJS Router页面切换问题:返回时原页面重载如何解决?

解决SolidJS Router返回页面重新加载的问题

SolidJS Router 默认在路由切换时会卸载不匹配路径的组件,导致调用history.back()返回时,原页面会重新初始化并加载,无法保留之前的状态。要实现页面缓存,可通过以下两种方式手动处理:

方式一:通过显示隐藏控制组件(简单直接)

将需要缓存的组件放在同一个容器中,用display样式控制显示与隐藏,避免组件被卸载:

import { Router, Routes, Route, useLocation } from "@solidjs/router";
import { Match } from "solid-js";
import Home from "./Home";
import User from "./User";

function RouteContainer() {
  const location = useLocation();

  return (
    <div>
      {/* 缓存Home组件,仅通过display控制显示 */}
      <div style={{ display: location.pathname === "/Home" ? "block" : "none" }}>
        <Home />
      </div>
      {/* User组件按需渲染,不缓存 */}
      <Match when={location.pathname === "/User"}>
        <User />
      </Match>
    </div>
  );
}

// 路由配置调整
function App() {
  return (
    <Router>
      <Routes>
        <Route path="/Home" component={RouteContainer} />
        <Route path="/User" component={RouteContainer} />
      </Routes>
    </Router>
  );
}

这种方式下,Home组件始终存在于DOM中,只是隐藏起来,返回时直接显示,完全保留之前的状态。

方式二:自定义缓存组件(更灵活)

实现一个通用的KeepAlive组件,用Map存储组件实例,按需渲染缓存的组件:

import { Router, useLocation } from "@solidjs/router";
import { createSignal, createEffect, JSX } from "solid-js";
import Home from "./Home";
import User from "./User";

// 通用缓存组件
function KeepAlive(props: { children: JSX.Element; cacheKey: string }) {
  const [cacheMap] = createSignal(new Map<string, JSX.Element>());

  // 首次渲染时缓存组件实例
  createEffect(() => {
    const key = props.cacheKey;
    const currentCache = cacheMap();
    if (!currentCache.has(key)) {
      currentCache.set(key, props.children);
    }
  });

  return cacheMap().get(props.cacheKey) || props.children;
}

function App() {
  const location = useLocation();

  return (
    <Router>
      <div>
        <KeepAlive cacheKey="home">
          {location.pathname === "/Home" && <Home />}
        </KeepAlive>
        <KeepAlive cacheKey="user">
          {location.pathname === "/User" && <User />}
        </KeepAlive>
      </div>
    </Router>
  );
}

注意事项

  • 缓存组件会持续占用内存,对于不需要保留状态的页面,建议使用默认路由渲染方式。
  • 若需清理特定缓存,可给KeepAlive添加方法,通过监听路由变化移除对应缓存项。

内容的提问来源于stack exchange,提问作者teacher-too

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:40:11