31 lines
751 B
TypeScript
31 lines
751 B
TypeScript
// 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>
|
|
);
|
|
};
|