React的mobx使用方式

一、創(chuàng)建文件

stores
----- auth.js 例子文件
----- index.js 總?cè)肟?/p>

二、安裝

yarn add mobx
yarn add mobx-react

三、書(shū)寫(xiě)相應(yīng)代碼

auth.js

  1. import相應(yīng)的文件
import { observable, action } from "mobx"
  1. 聲明class類(lèi),并導(dǎo)出
class AuthStore {
    @observable 變量名 = 值
    @boservable values = {
        username = "梁又文"
        sex = "男"
    }
    
    @action 方法名(參數(shù)) {
        console.log(參數(shù))
    }
    @action setName(name){
        this.values.username = name
    }
}

export { AuthSotre }

index.js

  1. import相應(yīng)文件
import React, { createContext, useContext } from "react"
import { 類(lèi)名 } from "../stores/文件名"
import { AuthSotre } from "../stores/auth"
  1. 創(chuàng)建Context對(duì)象
const context = createContext({
    定義方法名: new 類(lèi)名(),
    authStore: new AuthStore()
})
  1. 將Context對(duì)象全局導(dǎo)出
export const useStores = () => useContext(context)

四、配置package.json

  1. 將react隱藏的webpack暴露出來(lái),釋放之前請(qǐng)先提交代碼
yarn eject
  1. 安裝插件
yarn add @babel/plugin-proposal-decorators
  1. 修改package.json
"babel": {
    "plugins": [
        ["@babel/plugin-proposal-decorators", {"legacy": true}]
    ],
    "presets": [
        "react-app"
    ]
}

五、在組件中進(jìn)行使用

  1. import相應(yīng)文件
import { observer } from "mobx-react"
import { useStores } from "../stores"
  1. 使用observer監(jiān)控組件,并解構(gòu)我們需要的對(duì)象出來(lái)并使用
const Demo = observer(()=>{
    const { AuthStore } = useStores()
   
    return (
        <>
            <h1>我是Demo組件</>
        </>
    )
})
  1. 解構(gòu)后我們就可以使用該對(duì)象的屬性及方法
const Demo = observer(()=>{
    const { AuthStore } = useStores()
    
    const changeName = () => {
        AuthStore.setName("改名字后的梁又文")
    }
   
    return (
        <>
            <h1>我是Demo組件,我的名字叫{ AuthStore.values.username }</h1>
            <button onClick={changeName}>改名字</button>
        </>
    )
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容