Mobx介绍
是什么
一个可以和React良好配合的集中状态管理工具,mobx和react的关系,相当于vuex和vue。 同类工具还有:
- redux
- dva
- recoil
优势
- 简单: 编写无模板的极简代码来精准描述你的意图(原生js)
- 轻松实现最优渲染:依赖自动追踪最小渲染优化
- 架构自由:可移植,可测试
环境搭建
配置说明
Mobx是一个独立的响应式的库,可以独立于任何UI框架而存在,但是通常人们把它和React 来绑定使使用,用Mobx来做响应式数据建模,React作为UI视图框架渲染内容。
所以配置方面我们需要三个部分:
- 一个通过create-react-app 创建好的react项目环境
- mobx本身
- 一个链接mobx和react的中间部件
如何配置
-
使用 create-react-app初始化react项目
$ npx create-react-app reactapp
-
安装mobx和mobx-react-lite
$ yarn add mobx mobx-react-lite
创建Store
初始化mobx
-
src目录下新建store文件夹以及index.js(/src/store/index.js)
import React from 'react'; import TestStore from './test.Store'; class RootStore { constructor() { this.taskStore = new TestStore(); } } // 实例化 const context = React.createContext(new RootStore()); export const useStore = () => React.useContext(context);
-
store目录下新建test.Store.js对mobx进行模块化管理(/src/store/test.Store.js)
import { makeAutoObservable } from 'mobx'; class TestStore { count = 0; constructor() { makeAutoObservable(this); } // 添加 addTest() { this.count++; } } export default TestStore;
如何使用
在页面中引入store,使用中间件连接,实现数据响应式。
import { observer } from 'mobx-react-lite';
import { useStore } from '../../store/index';
function Test() {
const { testStore } = useStore();
return (
<div>
<span>{testStore.count}</span>
<button onClick={testStore.addTest}>点击</button>
</div>
);
}
export default observer(Test);
以上就可以完成简单的状态管理了。