wip
This commit is contained in:
28
stores/storeContext.tsx
Normal file
28
stores/storeContext.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
// 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>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user