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