import { action, makeObservable, observable } from 'mobx'; import { createContext, useContext } from 'react'; class Store { @observable count = 1; constructor() { makeObservable(this); } @action setCount = () => { this.count++ } } export const store = new Store(); export const StoreContext = createContext<Store>({} as Store); export const StoreProvider = StoreContext.Provider; export const useStore = (): Store => useContext(StoreContext);
main.tsx
import React from 'react'; import ReactDOM from 'react-dom'; import Login from '@/pages/Login'; import '@/assets/index.css'; import { RouterContainer } from './routes'; import '@arcgis/core/assets/esri/themes/light/main.css' import { UseRequestProvider } from 'ahooks'; import { service } from './axios' import { Provider } from 'mobx-react'; import { store, StoreProvider } from './store/mbox'; ReactDOM.render( <React.StrictMode> <UseRequestProvider value={{ requestMethod: (param) => service(param) }}> <StoreProvider value={store}> <RouterContainer /> </StoreProvider> </UseRequestProvider> </React.StrictMode>, document.getElementById('root') );
使用
import React, { useContext, useEffect, useRef } from 'react' import './index.less' import { useObserver } from 'mobx-react' import { useStore } from '@/store/mbox' const MapBox = () => { const ref = useRef<HTMLDivElement>(null); const store = useStore(); return useObserver(() => ( <> <div style={{ margin: '200px 0 0 200px', color: 'red' }}> <span>{store.count}</span> <button onClick={() => store.setCount()}>+</button> </div> </> )) } export default MapBox
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接