mobx-react 入门应用

mobx

  1. observer观测器: 带有观测器的react组件或者属性被mobx实时观测

  2. observable可观测对象: 有mobx 建立的可观测对象

  3. action 更新事件:标识观测对象的改变事件

Actions:一般可以改变观测变量状态的代码,类似于setState,严格模式下,只有在动作中才可以修改状态


mobx 4个函数
  1. state 状态 相当于数据的存放库

  2. Derivations : 驱动

  3. Computed value : 计算值 两个及以上状太生成一个新值

  4. reactions: 反应


安装包 npm install mobx mobx-react --save
创建store 实例class

import { configure, observable, action } from 'mobx'
import IRootStore from './modules/IRootStore'
import UserOptions from './modules/user'



class InteStore implements IRootStore {
    constructor(){
        this.initStore()
    }
    @observable
    UserStore!: UserOptions
   
    @action('初始化store')
    initStore = () => {
        this.UserStore = new UserOptions()
        
    }
}
export function StoreConfig() {
    return new InteStore();
}


创建userStore


import { action, computed, makeObservable, observable, runInAction } from "mobx";
import { UserInterFace } from './InterfaceStore/userInterface'

/**
 * 对应的PC端仪表盘数据
 */
class User {
   /**
    * id
    */
   @observable
   id: number | undefined;
   
   /**
    * name
    */
   @observable
   userInfo!: UserInterFace

   constructor() {
      makeObservable(this)
   }

  
   @action
   setUserInfo(userInfo: UserInterFace) {
        this.userInfo = userInfo
   }

   @action.bound
   setId(id: number | undefined) {
      this.id = id
   }


}
export default User;


全局注入store

import { Provider } from 'mobx-react';
import App from './App';
import { StoreConfig } from '../src/stores/index'
import ReactDOM from 'react-dom/client';
import Vconsole from 'vconsole'


const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
let store = StoreConfig();
root.render(
  <Provider {...store}>
    <App />
  </Provider>
);


函数使用mobx示例


import React, { useEffect, Suspense } from "react";
import { Outlet } from "react-router-dom";
import { observer, inject } from "mobx-react";
import IRootStore from "../stores/modules/IRootStore";
import { Icon } from '@nutui/nutui-react';
import { useSearchParams } from "react-router-dom";
import { queryLoginUser } from '../api/beefiles'
                   
const Home = inject('UserStore')(observer((props: IRootStore) => {
    // inject('UserStore') 注入user store 信息
    const { UserStore } = props // 获取UserStore 数据

    const [searchParams] = useSearchParams();
    let token: string | null = searchParams.get("token");
    if (token) {
        sessionStorage.setItem("token", token);
    }

    useEffect(() => {
        const data = {}
        queryLoginUser(data).then((res) => {
            if (res && (res as any).code === 200) {}
            UserStore?.setUserInfo(res.data) // 使用store 方法 设置store user数据
        })
    }, [])

   
   
    return ( 
        <Suspense 
            fallback={ 
                <div 
                    style={{ 
                        width: "100vw", 
                        height: "100vh", 
                        display: "flex", 
                        alignItems: "center", 
                        justifyContent: "center", 
                        flexDirection: "column", 
                    }} 
                > 
                    <Icon name="loading"></Icon>
                </div> 
            } 
        >
            <div className="App app-box" id="App">
                {/* 有嵌套路由的场景需要使用 */}
                <Outlet></Outlet>
            </div>
        </Suspense> 
    );
}));

export default Home;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值