mobx的使用及配置装饰器

1、装饰器配置

yarn add -D react-app-rewired customize-cra  @babel/core @babel/plugin-proposal-decorators @babel/preset-env
  • 项目根目录新建 .babelrc 文件

配置babel插件,开启装饰器功能

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

  • 项目根目录新建 config-overrides.js 文件
const path = require('path');
const { override, addDecoratorsLegacy } = require('customize-cra');

function resolve(dir) {
	return path.join(__dirname, dir);
}

const customize = () => (config, env) => {
	config.resolve.alias['@'] = resolve('src');
	if (env === 'production') {
		config.externals = {
			react: 'React',
			'react-dom': 'ReactDOM',
		};
	}

	return config;
};
module.exports = override(addDecoratorsLegacy(), customize());

更改项目启动方式
package.json文件中修改scripts脚本命令

"scripts": {
	"start": "react-app-rewired start",
	"build": "react-app-rewired build",
	"test": "react-app-rewired test",
	"eject": "react-scripts eject"
},

【注】配置完以上内容,重新启动项目

2、 mobx配置store

import { observable, action, runInAction, configure } from 'mobx';

// 开启mobx的严格模式:只允许在当前store中更新数据,外部页面修改store数据将会报错
configure({
	enforceActions: 'always',
});

class Store {
	// 将普通js数据转化成mobx可观察数据
	@observable totalCount = 0;
	@observable loading = false;
	@observable list = [];

	@action getTableData = async () => {
		console.log('get-table-data');
		const res = await axios.get('http://0.0.0.0/api/test');

		// 异步执行需要在 runInAction 中更新store中的数据
		runInAction(() => {
			this.list = res;
		});
	};
}

const store = new Store();

export default store;

不使用装饰器配置方式

import { observable, action } from 'mobx';

const store = observable(
	{
		totalCount: 0,
		loading: false,
		list: [],
		getTableData: () => {},
	},
	{
		getTableData: action,
	},
);

export default store;

【推荐mobx搭配插件】immutable

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值