SolidJS Router page switching issues

438 views Asked by At

Use the solidjs router to jump to a new page, the original page will be destroyed, resulting in the use of history.back(); When you return, the original page is reloaded.

<Router>
  <Routes>
    <Route path="/Home" component={Home} />
    <Route path="/User" component={User} /> 
  </Routes>
</Router>

For example, switch from the home page to the User page, and then use history.back() for the user page Go back, Home page refreshes again. This is not the effect I want. How can I keep the rendered page?

1

There are 1 answers

2
snnsnn On

Router disposes a component when you navigate away from it. That is reasonable because so many parameters may have been been changed between two visits, otherwise the using previously rendered component would give you static pages.

If you don't want to re-render a component you can wrap it into a detached root using createRoot and dispose it manually when you done with it.

A memoized component would also work but there is no way to trigger onDispose function on a memoized value.

import { Link, Route, Router, Routes, hashIntegration } from '@solidjs/router';
import { Component, createRoot, onMount } from 'solid-js';
import { render } from 'solid-js/web';

const Home = () => {
  onMount(() => console.log('Home Mounted'));
  return <div>Home</div>;
};

const Blog = () => {
  onMount(() => console.log('Blog Mounted'));
  return <div>Blog</div>;
};

const Contact = () => {
  onMount(() => console.log('Contact Mounted'));
  return <div>Contact</div>;
};

let dispose: () => void;
const home = createRoot((disposer) => {
  dispose = disposer;
  return <Home />;
}) as unknown as Component<{}>;

window.onunload = dispose!;

const App = () => {
  return (
    <Router source={hashIntegration()}>
      <ul>
        <li><Link href="/home">Home</Link></li>
        <li><Link href="/blog">Blog</Link></li>
        <li><Link href="/contact">Contact</Link></li>
      </ul>
      <Routes>
        <Route path="/home" component={home} />
        <Route path="/blog" component={Blog} />
        <Route path="/contact" component={Contact} />
      </Routes>
    </Router>
  );
};

render(App, document.body);

There is also a Github discussion on the issue which you can find at https://github.com/solidjs/solid/discussions/1054#discussioncomment-6711906. Currently I added the same answer but you may find some additions in the future.