This commit is contained in:
2025-03-20 18:06:22 +08:00
parent 9ad083b014
commit a2ef989b75
4 changed files with 71 additions and 1 deletions

16
lib/client/storage.ts Normal file
View File

@@ -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"
}
};
};

View File

@@ -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 (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<StoreProvider initialData={initialState}>
{children}
</StoreProvider>
</body>
</html>
);

18
stores/counterStore.ts Normal file
View File

@@ -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;
}
}

30
stores/storeContext.ts Normal file
View File

@@ -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 (
<Provider value={stores}>
{children}
</Provider>
);
};