From a2ef989b757c4174c0eb18ee6a835b8566500000 Mon Sep 17 00:00:00 2001 From: eeymoo Date: Thu, 20 Mar 2025 18:06:22 +0800 Subject: [PATCH] wip --- lib/client/storage.ts | 16 ++++++++++++++++ app/layout.tsx | 8 +++++++- stores/counterStore.ts | 18 ++++++++++++++++++ stores/storeContext.ts | 30 ++++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 lib/client/storage.ts create mode 100644 stores/counterStore.ts create mode 100644 stores/storeContext.ts diff --git a/ lib/client/storage.ts b/ lib/client/storage.ts new file mode 100644 index 0000000..38f0bc8 --- /dev/null +++ b/ lib/client/storage.ts @@ -0,0 +1,16 @@ +// lib/client/storage.ts +export const CLIENT_STORAGE_KEYS = { + THEME: "theme", + LANG: "lang" +} as const; + +export const getInitialState = () => { + if (typeof window === "undefined") return {}; + + return { + uiStore: { + theme: localStorage.getItem(CLIENT_STORAGE_KEYS.THEME) || "light", + language: localStorage.getItem(CLIENT_STORAGE_KEYS.LANG) || "zh-CN" + } + }; +}; diff --git a/app/layout.tsx b/app/layout.tsx index f7fa87e..d765b31 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -1,6 +1,8 @@ import type { Metadata } from "next"; import { Geist, Geist_Mono } from "next/font/google"; import "./globals.css"; +import { StoreProvider } from "../stores/storeContext"; +import { getInitialState } from "@/ lib/client/storage"; const geistSans = Geist({ variable: "--font-geist-sans", @@ -22,12 +24,16 @@ export default function RootLayout({ }: Readonly<{ children: React.ReactNode; }>) { + const initialState = getInitialState(); + return ( - {children} + + {children} + ); diff --git a/stores/counterStore.ts b/stores/counterStore.ts new file mode 100644 index 0000000..c7b12e3 --- /dev/null +++ b/stores/counterStore.ts @@ -0,0 +1,18 @@ +// stores/counterStore.ts +import { makeAutoObservable } from "mobx"; + +export class CounterStore { + count = 0; + + constructor() { + makeAutoObservable(this); + } + + increment() { + this.count += 1; + } + + decrement() { + this.count -= 1; + } +} diff --git a/stores/storeContext.ts b/stores/storeContext.ts new file mode 100644 index 0000000..0371cf4 --- /dev/null +++ b/stores/storeContext.ts @@ -0,0 +1,30 @@ +// stores/storeContext.ts +import { createContext, useContext } from "react"; +import { CounterStore } from "./counterStore"; + +const StoreContext = createContext<{ + counterStore: CounterStore; +}>(null!); + +export const useStores = () => useContext(StoreContext); + +export const initializeStores = (initialData = {}) => { + const counterStore = new CounterStore(); + + // 服务端预取数据注入 + if (initialData.counterStore) { + counterStore.count = initialData.counterStore.count; + } + + return { counterStore }; +}; + +export const StoreProvider = ({ children, initialData }) => { + const stores = initializeStores(initialData); + const { Provider } = StoreContext; + return ( + + {children} + + ); +};