React Context 和 Mobx結(jié)合

1. Context 基礎(chǔ)

參考:

2. mobx-react 基礎(chǔ)

參考:

3. Context 和 mobx 結(jié)合參考示例

參考:

4 具體實現(xiàn)

上面關(guān)于mobx的文檔是真的很難讀,所以時間有限,長話短說,直接上代碼,其他的以后再補充

  1. 創(chuàng)建store容器和獲取store的函數(shù)
// store.js 
import React, { createContext, useContext } from 'react'
import { observable, action, configure } from 'mobx'
import { useLocalStore } from 'mobx-react'

// 強制使用action
configure({enforceActions: 'observed'})

// 創(chuàng)建數(shù)據(jù)由于使用了裝飾器 所以使用class聲明
class Store {
    @observable count = 0

    // 注意this 
    @action
    add = () => {
        this.count += 1
    }

    @action.bound
    reduce() {
        this.count -= 1
    }
}

// 創(chuàng)建context
const StoreContext = createContext(new Store())

// 創(chuàng)建context容器 就是一個函數(shù)組件
export const Provider = ({children}) => {
    // useLocalStore的參數(shù)是一個函數(shù) 返回數(shù)據(jù)源
    const store = useLocalStore(() => new Store())
    return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}

// 其他組件獲取store
export const useStore = () => {
    return useContext(StoreContext)
}
  1. 使用store容器
import React from 'react';
import ReactDOM from 'react-dom';
// 根組件
import App from './App';
// 引入store.js
import { Provider } from '@/mobx/store'

// 和redux很像 用上面創(chuàng)建的容器包裹根組件 這樣就能實現(xiàn)全局store
ReactDOM.render(<Provider><App/></Provider>, document.getElementById('root'));
  1. 在組件中使用store
import React, {Fragment} from 'react'
import { observer } from 'mobx-react'
import { useStore } from '@/mobx/store'

// 這里是用的函數(shù)組件 class組件直接在上面用@observer就行了
const Home = observer((props) => {
  const { count, add, reduce } = useStore()
  return (
    <Fragment>
        <p>{count}</p>
        <button onClick={() => {add()}}>+</button>
        <button onClick={() => {reduce()}}>-</button>
    </Fragment>
  )
})

export default Home

下面總結(jié)一下步驟

還有 13% 的精彩內(nèi)容
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
支付 ¥2.33 繼續(xù)閱讀

推薦閱讀更多精彩內(nèi)容