wip
This commit is contained in:
18
stores/counterStore.ts
Normal file
18
stores/counterStore.ts
Normal 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
30
stores/storeContext.ts
Normal 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>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user