12.mobx 6的安装与使用,启用装饰器语法

  1. 下载相关包
npm install mobx mobx-react --save
npm install -D
  @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties
  @babel/plugin-proposal-private-methods @babel/plugin-proposal-private-property-in-object
  1. 配置babel文件(.babelrc)
"plugins": [
    ...
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    ["@babel/plugin-proposal-private-methods", { "loose": true }],
    ["@babel/plugin-proposal-private-property-in-object", { "loose": true }],
    ...
]

// 如果是ts项目,需要在tsconfig.json中加入这一句话

{
    "compilerOptions": {
        ...
        "experimentalDecorators": true,
        ...
    }
}
  1. 新建store文件夹,并创建index.tsx主文件以及相关store类,相关代码如下
    ● index.tsx
import ListStore from './ListStore';

const stores = {
  ListStore,
};

export { stores };
export default stores;

● 新建一个ListStore测试类

import { action, makeObservable, observable, computed } from 'mobx';

class ListStore {
  @observable count: number = 0;
  @observable selectUserList: Array<{ name: string; key: string }> = [];

  @action.bound
  add() {
    this.count += 1;
  }

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

  @computed
  get countComputedVal() {
    return this.count * 2;
  }

  @action.bound
  handleSelectUserList(userList: Array<{ name: string; key: string }>) {
    this.selectUserList = userList;
  }

  constructor() {
    makeObservable(this);
  }
}

export default new ListStore();
  1. 导入index.tsx主入文件中,并配置
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'mobx-react';

import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import moment from 'moment';
import App from './app';
import 'moment/locale/zh-cn';
moment.locale('en');

import stores from '@/store';

import 'antd/dist/antd.less';
import './global.less';


const root = createRoot(document.getElementById('root'));


root.render(
  <Provider {...stores}>
    <ConfigProvider
      locale={zhCN}
      getPopupContainer={(node) => document.body}
    >
      <App />
    </ConfigProvider>
  </Provider>,
);
5. 在页面中使用mobx中的状态,代码如下:
import { inject, observer } from 'mobx-react';
import React from 'react';
import { Button } from 'antd';

function Home(props) {
  const { ListStore } = props;
  const { count, add, sub, selectUserList } = ListStore;

  return (
    <div className="btn-div">
      <div>数值:{count}</div>
      <Button onClick={add}>+</Button>
      <Button onClick={sub}>-</Button>
      <div>
        已选择的人员:{selectUserList.length > 0 ? selectUserList.map((v) => v.name).join('、') : '暂无选中人员'}
      </div>
    </div>
  );
}

export default inject('ListStore')(observer(Home));

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值