1. 程式人生 > 其它 >react-mobx,react-mobx6使用案例

react-mobx,react-mobx6使用案例


腳手架 create-react-app

目錄

一、安裝

二、配置package.json

三、定義mobx的store

四、在頁面中使用mobx,並且通過action 改變mobx


一、安裝

//npm yarn 隨需求,儘量不要混用,混用有些資源可能會出現掉包
yarn add mobx
yarn add mobx-react


// 版本號
"mobx": "^6.3.2",
"mobx-react": "^7.2.0",

二、配置package.json

1.把隱藏的webpack暴露出來,釋放之前記得請先提交程式碼 git commit 一次

yarn run eject

2.安裝@babel/plugin-proposal-decorators 外掛 必須的

yarn add @babel/plugin-proposal-decorators


3.修改新增 package.json配置 (手動)

"babel": {
    "plugins": [
        ["@babel/plugin-proposal-decorators", {"legacy": true}]
    ],
    "presets": [
        "react-app"
    ]
}

三、定義mobx的store

1.目錄機構(mobx支援多個多個狀態模組)

stores
----- auth.js 模組1

----- test.js模組2
----- index.js 總入口

2.模組 auth.js

// auth.js和test.js 一模一樣 展示auth.js做案例
// @action.bound 和  @action 區別 https://cn.mobx.js.org/refguide/action.html
import { observable, action, computed } from "mobx";
import { makeObservable} from "mobx";

export class AuthStore {
    
// 定義變數 @observable name = 'zhangsan000'; @observable sex = '男'; @observable userObj = { name: 'zhangsan000', age: 233, token: '12345689' } // 初始化 constructor() { // mobx6版本以後 必須得在初始化加makeObservable makeObservable(this); } // 動作(bound 可以自動繫結this 防止this 指向改變) @action.bound setName(v) { console.log('觸發action'); this.name = v; } @action setUserObj(obj) { this.userObj = obj; } // 計算屬性 @computed get titleName(){ return this.name+'___111'; } }

3.定義匯出出口index.js

import { AuthStore } from "./auth";
import { TestStore } from "./test";

export const store = {
    authStore: new AuthStore(),
    testStore: new TestStore()
};

  

4.在react 工程入口 匯入

import { store } from  './store/index';
import { Provider} from 'mobx-react';

ReactDOM.render(
  <React.StrictMode>
    <Provider store = {store}>
      <App  />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

四、在頁面中使用mobx,並且通過action 改變mobx

import React, { Component, PureComponent } from "react";
import { observer, inject } from 'mobx-react';

@inject( 'store')
@observer
class Index extends PureComponent {
    
    constructor(props) {
        super(props);
        console.log(this.props);
        this.state = {  };
    }
    render() {
        const { authStore, testStore } = this.props.store;
        return (
            <div>
                {authStore.name}/
                
                {testStore.name}/

                {authStore.titleName}
                <br />
                <button onClick = { () => { 
                    authStore.setName(new Date().getTime()); 
                } }>點選按鈕觸發action</button>
            </div>
        );
    }
}

export default Index;