当前位置:网站首页>MobX初探
MobX初探
2022-06-09 20:06:00 【前端阿龙】
背景介绍
- 相对于redux来说简单,同时也是个可扩展的状态管理库
- MobX由Mendix, Coinbase, Facebook开源和众多个人赞助商所赞助
- React和MobX是一对强力组合,React负责渲染应用的状态,MobX负责管理应用状态供React使用
浏览器支持
- MobX5版本运行在任何支持ES6 proxy的浏览器上面都可以,不支持IE11, Node.js6
- MobX4可以运行在任何支持ES5的浏览器上
- MobX5和MobX4的API是相同的
准备工作
- 因为浏览器不支持装饰器语法,所以增加配置
启用装饰器语法支持
方式一:
1. npm run eject
2. npm install @babel/plugin-proposal-decorators
3. package.json
"babel": {
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
方式二:
1. npm install react-app-rewired @babel/plugin-proposal-decorators customize-cra
2. 在项目根目录下创建 config-overrides.js
const {
override, addDecoratorsLegacy } = require("customize-cra");
module.exports = override(addDecoratorsLegacy());
3. package.json
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
}
解决vscode编辑器关于装饰器语法的警告
"javascript.implicitProjectConfig.experimentalDecorators": true
生成项目
- 下载MobX
npm install mobx mobx-react - 创建存储状态的对象
// stores/TodoStore.js
import {
observable } from 'mobx'
class TodoStore {
// observable表示是可观测的数据
@observable test: '';
@observable todos = [];
//向todos里面添加数据 更改可观测数据前缀@action .bound改变this指向
@action.bound todoAdd () {
}
}
const todo = new TodoStore();
export default todo;
- 把todo对象放到全局
//在index.js入口文件中引入
import todo from './stores/TodoStore';
import {
Provider } from 'mobx-react';
ReactDOM.render(
<Provider todo={
todo}><App /></Provider>,
document.getElementById('root');
);
// 在需要用到全局状态的组件中使用装饰器来把todo注入到这个组件的props里面,同时还需要又个装饰器来监听改变更新视图
import React, {
Component } from 'react';
import {
inject, observer } from 'mobx-react';
@inject('todo'); //注入store实例
@observer //监听store实例的改变
class AddTodo extends Component {
render() {
const {
test } = this.props.todo;
return (
<header className="header">
{
test}
</header>
)
}
}
export default AddTodo;
边栏推荐
- Kalman filter (KF) unscented Kalman filter (UKF)
- Question bank and answers for the 2022 National latest fire facility operator (senior fire facility operator) examination
- Unity UI slider component
- 【RK2206】4. Mqtt example
- Unity-UI-Slider组件
- 杰理之 图传、录卡或者UVC显示的摄像头-高帧率说明【篇】
- Unity upgrade project to URP
- 【opencvsharpDNN】OpenCvSharp中YoloV3和Caffe的实现示例
- Look at other people's text recognition system. It's called elegant!
- 高通:将坚持多元化的代工战略,关注英特尔代工商务合作条件
猜你喜欢
随机推荐
asp.net txt读写
asp.net DataTable和Table的一些笔记
2022山东健博会,食疗养生与滋补健康展,健康管理与精准医学展
Potential functions commonly used in lammps and collection of crystal library resources
杰理之有关摄像头的应用【篇】
MySQL data type
Leetcode 1984. Différence minimale entre les notes des élèves (Oui, résolu)
Set的创建和遍历方法
Logback日志配置文件添加颜色区分
VNCTF 2022 InterestingPHP
如何查看 Tekton 的流水线指标
Unity将Project升级至URP
杰理之有关摄像头帧数,以及图层【篇】
Edge浏览器设置网速限制
Modelarts second training notes
mysql数据类型
Unity-UI-Slider组件
asp. Net datatable and some notes of table
Shell script installing Prometheus and node_ exporter
Système de fichiers racine









