mobx笔记
入門案例
1、環(huán)境搭建
創(chuàng)建項目
mkdir my-app cd my-app npm init -y安裝依賴
cnpm i webpack webpack-cli -D cnpm i html-webpack-plugin -D cnpm i babel-loader @babel/core @babel/preset-env -D cnpm i @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties -D cnpm i @babel/plugin-transform-runtime -D cnpm i @babel/runtime -S cnpm i mobx -S構(gòu)建項目結(jié)構(gòu)
按照以下目錄結(jié)構(gòu)創(chuàng)建文件
- my-app|-- src 源文件目錄|-- index.js 入口文件|-- public 靜態(tài)資源目錄|-- index.html|-- webpack.config.js|-- dist 打包后的靜態(tài)文件目錄編寫 index.html 文件:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title> </head> <body></body> </html>編寫 webpack.config.js 配置文件
const path = require('path'); const HtmlWebPackPlugin = require('html-webpack-plugin');module.exports = {mode: 'development',entry: path.resolve(__dirname, 'src/index.js'),output: {path: path.resolve(__dirname, 'dist'),filename: 'main.js'},module: {rules: [{test: /\.js$/,exclude: /node_modules/,use: {loader: 'babel-loader',options: {presets: ['@babel/preset-env'],plugins: [//支持裝飾器["@babel/plugin-proposal-decorators", { "legacy": true }],["@babel/plugin-proposal-class-properties", { "loose" : true }],['@babel/plugin-transform-runtime']]}}}]},plugins:[new HtmlWebPackPlugin({template: 'public/index.html',filename: 'index.html',inject: true})] }在 package.json 文件中配置打包命令:
{"scripts": {"build": "webpack --mode production"} }2、Mobx核心API
下面的代碼需要在 src/index.js 中完成。
2.1、observable可觀察的狀態(tài)
- map
- object
- array
- 基礎(chǔ)類型
2.2、 observable裝飾器
import { observable } from 'mobx'class Store{@observable arr = [];@observable obj = {a: 'htllo'};@observable map = new Map();@observable str = 'hello';@observable num = 123;@observable bool = false; }const store = new Store();console.log(store); console.log(store.obj.a); console.log(store.num);注意:vscode編譯器中,js文件使用裝飾器會報紅。解決方式:
在根目錄編寫 jsconfig.json
{"compilerOptions": {"module": "commonjs","target": "es6","experimentalDecorators": true},"include": ["src/**/*"] }2.3、對 observables 作出響應
computed
計算值是可以根據(jù)現(xiàn)有的狀態(tài)或其它計算值衍生出的值, 跟vue中的computed非常相似。
import { observable, computed } from 'mobx'var name = observable.box("John");var upperCaseName = computed(() =>name.get().toUpperCase() );//name的屬性值 console.log("name:",name.get()); console.log("轉(zhuǎn)換后:",upperCaseName.get());//對computed返回值做監(jiān)聽 var disposer = upperCaseName.observe_(change => {console.log("監(jiān)聽到數(shù)據(jù)變化:",change.newValue,change.oldValue) });//對observable觀察的屬性做修改 name.set("Dave"); name.set("Lily");autorun
import { observable, computed, autorun } from 'mobx'const arry = observable([1,2,3])const result = computed(()=>{return arry.reduce((total,item)=>{return total + item}) }) //得到計算后的結(jié)果 console.log(result.get());//會先觸發(fā)一次監(jiān)聽,然后每次修改 arry 都會觸發(fā) autorun(()=>{console.log('監(jiān)聽到修改的結(jié)果:', result.get()); })//修改 observable 被觀察對象的值 arry.push(4) arry.push(5)2.4、改變 observables狀態(tài)
import { observable, action } from 'mobx'class Store {@observable num = 10@action add(){return this.num += 1} }const store = new Store()console.log(store.add());3、案例應用
在react中使用mobx,需要借助mobx-react。
它的功能相當于在react中使用redux,需要借助react-redux。
首先來搭建環(huán)境:
create-react-app react-app cd react-app npm run eject npm i @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties -D npm i mobx mobx-react -S修改package.json中babel的配置:
"babel": {"presets": ["react-app"],"plugins": [["@babel/plugin-proposal-decorators",{"legacy": true}],["@babel/plugin-proposal-class-properties",{"loose": true}]]}注意:vscode編譯器中,js文件使用裝飾器會報紅。解決方式:
在根目錄編寫寫jsconfig.json
{"compilerOptions": {"module": "commonjs","target": "es6","experimentalDecorators": true},"include": ["src/**/*"] }在 src 目錄下創(chuàng)建 store.js ,作為項目的全局狀態(tài)管理
import {observable, computed, action} from 'mobx'class Store {@observable num = 10@computed get sumOne() {return this.num += 1}@action add = ()=>{console.log(this);return this.num += 10} }const store = new Store()export default store在其他組件中就可以使用了,例如在 index.js 中使用
import React from 'react'; import ReactDOM from 'react-dom'; import store from './store';console.log(store.num); console.log(store.sumOne); console.log(store.add());ReactDOM.render(<div>hello</div>,document.getElementById('root'));總結(jié)
- 上一篇: 深入解析final关键字的用法
- 下一篇: css-字体样式