问题描述
在 Sapper 应用中,我希望能够保留某些 UI 组件的状态,以便在用户返回使用这些组件的页面时导航应用而不会丢失状态.
In a Sapper app, I want to be able to persist the state of some UI components so I can navigate the app without losing state when the user returns to the pages using those components.
在仅限 Svelte 的应用程序中,这通常通过使用 sessionStorage
或 localStorage
API 的自定义商店完成.一个很好的例子可以在 R. Mark Volkmann 的书 Svelte and Sapper in Action 中找到,第 6.24 节:
In a Svelte-only app, this is usually done with a custom store that uses the sessionStorage
or localStorage
API. A good example of that can be found in R. Mark Volkmann's book Svelte and Sapper in Action, §6.24:
store-util.js
import {writable} from 'svelte/store';
function persist(key, value) {
sessionStorage.setItem(key, JSON.stringify(value));
}
export function writableSession(key, initialValue) {
const sessionValue = JSON.parse(sessionStorage.getItem(key));
if (!sessionValue) persist(key, initialValue);
const store = writable(sessionValue || initialValue);
store.subscribe(value => persist(key, value));
return store;
}
不幸的是,在 Sapper 中使用这种方式会立即中断,因为脚本首先在服务器上运行,其中 sessionStorage
未定义.有一些方法可以阻止某些部分的代码在服务器上运行(使用组件中的 onMount
生命周期函数,或者检查 process.browser === true
),但是这在这里似乎不可能.
Unfortunately, using stores that way breaks immediately in Sapper because the scripts run on the server first, where sessionStorage
is not defined. There are ways to prevent some parts of code from running on the server (using the onMount
lifecycle function in a component, or checking process.browser === true
), but that doesn't seem possible here.
在本地保留一些状态看起来是一个非常常见的用例,所以我想知道在 Sapper 应用程序中执行此操作的正确方法是什么(考虑到我什至还没有找到错误的方法).
Persisting some state locally looks like a very common use case so I'm wondering what's the right way to do it in a Sapper app (considering that I haven't even found the wrong way).
推荐答案
为 SSR 提供一个虚拟存储.
Provide a dummy store for SSR.
总是可以使用诸如 typeof localStorage !== 'undefined'
之类的东西来进行特征检测.
It is always possible to do feature detection with something like typeof localStorage !== 'undefined'
.
您的组件代码将在浏览器中重新运行,即使页面已通过 SSR.这意味着,如果它被提供给不同的存储,则仅浏览器的值将接管并更新现有状态(从服务器继承).
Your component code will re-run in the browser, even if the page was SSR'd. This means that if it is fed a different store, the browser-only values will take over and update existing state (inherited from the server).
请参阅此答案的示例.
这篇关于如何在 Sapper 中保存 UI 组件状态数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!