可写存储在页面更改时被覆盖,SvelteKit

Dan*_*ita 2 store writable typescript sveltekit

I 存储在可写存储中的值

import { writable } from 'svelte/store'

export const user = writable(null)
export const isLoggedIn = writable(false)

Run Code Online (Sandbox Code Playgroud)

然后我导入这些值并将它们设置在索引中

 import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
  import { user, isLoggedIn } from "../stores/authStore";
  const provider = new GoogleAuthProvider();
  const auth = getAuth();
  function signIn() {
    signInWithPopup(auth, provider)
      .then((result) => {
        user.set(result.user) 
        isLoggedIn.set(true);
        console.log($isLoggedIn);
        console.log($user.email);
        if ($user.email.includes(".edu")) window.location.href = "/home";
        else window.location.href = "/Sorry";
        //sign user into db
      })
      .catch((error) => {
        console.log("Someting wrong");
        console.error(error);
      });
  }
Run Code Online (Sandbox Code Playgroud)

当我更改页面并使用再次打印值时

console.log($userValue, $isLoggedIn)
Run Code Online (Sandbox Code Playgroud)

它返回默认值

console.log($userValue, $isLoggedIn)
Run Code Online (Sandbox Code Playgroud)

我不知道我是否使用了错误的语法,或者也许我需要使用 cookie,但我对 sveltekit 非常熟悉,并且希望得到一些帮助。

mrk*_*shi 5

使用window.location.href = '/new-path';会使您的浏览器完全导航离开当前页面。它将卸载当前页面并加载新页面,因此当前页面上的任何状态都将丢失(包括变量和存储)。

在 SvelteKit 中,您可以使用该goto功能来重定向用户。在客户端中使用时,它将通过客户端路由器触发页内导航,因此您可以保留所有状态:

import { goto } from '$app/navigation';

if (someCondition) {
    goto('/home');
}
Run Code Online (Sandbox Code Playgroud)