6 changed files with 76 additions and 2 deletions
-
2package.json
-
5src/App.jsx
-
5src/main.jsx
-
18src/store/CountStore.js
-
24src/store/index.jsx
-
24yarn.lock
@ -0,0 +1,18 @@ |
|||
import { action, makeObservable, observable } from 'mobx' |
|||
/** |
|||
* 状态被标记为observable |
|||
* 更改状态的方法标记为action.bound |
|||
* 组件使用observer方法包裹 |
|||
*/ |
|||
export default class CountStore { |
|||
constructor() { |
|||
this.count = 0 |
|||
makeObservable(this, { |
|||
count: observable, |
|||
increment: action.bound, |
|||
}) |
|||
} |
|||
increment() { |
|||
this.count++ |
|||
} |
|||
} |
@ -0,0 +1,24 @@ |
|||
import CountStore from './CountStore' |
|||
import { createContext, useContext } from 'react' |
|||
|
|||
class RootStore { |
|||
constructor() { |
|||
this.countStore = new CountStore() |
|||
} |
|||
} |
|||
|
|||
const rootStore = new RootStore() |
|||
|
|||
const RootStoreContext = createContext() |
|||
|
|||
export const RootStoreProvider = ({ children }) => { |
|||
return ( |
|||
<RootStoreContext.Provider value={rootStore}> |
|||
{children} |
|||
</RootStoreContext.Provider> |
|||
) |
|||
} |
|||
|
|||
export const useRootStore = () => { |
|||
return useContext(RootStoreContext) |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue