分类
react

React mobx共享全局变量

mobx持久性变量实现方式。会有一下几个步骤:1.定义store。2.暴露store。3.引入在.tsx引入store。4.在.tsx内使用store

定义Store

// store.ts
import { makeAutoObservable } from 'mobx'

class Store {
  visible = false
  constructor() {
    makeAutoObservable(this)
  }
}

export default Store

暴露Store

// context.ts
import React from 'react'
import Store from './store'

const GlobalContext = React.createContext<Store>(new Store())

export default GlobalContext

引入Store

// index.tsx
import React, { FC } from 'react'
import Store from './store'
import GlobalContext from './context'
import { observer, useLocalObservable } from 'mobx-react'

const Home:FC = () => {
  const store = useLocalObservable(() => new Store())
  return (<GlobalContext.Provider value={store}>...</GlobalContext.Provider>)
}

export default observer(Home)

使用Store

import GlobalContext from '../context'
import React, { FC, useContext } from 'react'

const LongPage:FC<...> = () => {
  const globalStore = useContext(GlobalContext)
}
export default observer(LongPage)

由zhuishao

github:https://github.com/zhuishao/

发表评论

电子邮件地址不会被公开。 必填项已用*标注