From 498c0a8e41ee47cc103b5a9944edc8d59bd529c1 Mon Sep 17 00:00:00 2001 From: meetqy Date: Mon, 23 Jan 2023 15:46:01 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E2=9A=A1=EF=B8=8F=20localstorage=20?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E4=B8=BB=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/_app.tsx | 13 ++++++++++--- store/index.ts | 11 +++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/pages/_app.tsx b/pages/_app.tsx index 3c7d80c2..d2797af8 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -1,12 +1,13 @@ import { MyLayout } from "@/components/Layout"; -import { RecoilRoot, useRecoilValue } from "recoil"; +import { RecoilRoot, useRecoilState } from "recoil"; import zhCN from "antd/locale/zh_CN"; import "antd/dist/reset.css"; import "@/styles/global.css"; import { ConfigProvider, theme } from "antd"; -import { themeState } from "@/store"; +import { ThemeMode, themeState } from "@/store"; import Head from "next/head"; import Pkg from "@/package.json"; +import { useEffect } from "react"; export default function MyApp(props) { return ( @@ -17,7 +18,13 @@ export default function MyApp(props) { } const Container = ({ Component, pageProps }) => { - const themeMode = useRecoilValue(themeState); + const [themeMode, setThemeMode] = useRecoilState(themeState); + + // 初始化 store + useEffect(() => { + const localMode = localStorage.getItem("use-local-mode") as ThemeMode; + setThemeMode(localMode || "light"); + }, [setThemeMode]); return ( <> diff --git a/store/index.ts b/store/index.ts index a86d1b4e..77059db5 100644 --- a/store/index.ts +++ b/store/index.ts @@ -42,9 +42,16 @@ export const rightBasicState = atom({ // layout content ref export const LayoutContentRefContext = createContext({ current: null }); -type Theme = "light" | "dark"; // 主题 +export type ThemeMode = "light" | "dark"; export const themeState = atom({ key: "themeState", - default: "light" as Theme, + default: "light" as ThemeMode, + effects_UNSTABLE: [ + ({ onSet }) => { + onSet((val) => { + localStorage.setItem("use-local-mode", val); + }); + }, + ], });