30 lines
782 B
TypeScript
30 lines
782 B
TypeScript
"use client";
|
|
// 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 (
|
|
<StoreContext.Provider value={stores}>{children}</StoreContext.Provider>
|
|
);
|
|
};
|