Skip to content

Commit

Permalink
perf: ⚡️ localstorage 记录主题
Browse files Browse the repository at this point in the history
  • Loading branch information
meetqy committed Jan 23, 2023
1 parent 78ab80c commit 498c0a8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
13 changes: 10 additions & 3 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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 (
<>
Expand Down
11 changes: 9 additions & 2 deletions store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
},
],
});

0 comments on commit 498c0a8

Please sign in to comment.