# fed-mobx-4-2 **Repository Path**: dadami/fed-mobx-4-2 ## Basic Information - **Project Name**: fed-mobx-4-2 - **Description**: mobx - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-01-17 - **Last Updated**: 2021-03-17 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### Mobx 工作流程 action -> state -> Views ```js npm install mobx mobx-react // store 文件夹 import { Provider } from 'mobx-react'; import counter from './store/countStore' , document.getElementById('root') ``` ### 7 更正类中的普通函数的this 指向 ```js @aciton increment = () => { this.count = this.count + 1; } @aciton decrement = () => { this.count = this.count - 1; } @aciton decrement () { this.count = this.count - 1; } // 报错 @aciton.bound decrement () { this.count = this.count - 1; } // 正确 ``` ### 异步更新状态一 ```js npm install axios import axios from 'axios' @action.bound async getData () { const { data } = await axios.get('https://api.github.com/users') runInAction(() => { this.users = data }) } ``` ### 异步更新状态一 ```js import { flow } from 'mobx'; // flow 更正this getData = flow(function* () { let { data } = yield axios.get('https://api.github.com/users') this.users = data }).bind(this) ``` ### Mobx 数据监测 5.1 computed 计算值 1. 什么是计算值 计算值是可以根据现有的状态或其他计算值衍生出的值 2.什么时候使用计算值 将复杂的业务逻辑从模版中进行抽离 ```js import { observable, action, computed } from 'mobx'; class BirdStore { @observale count = 10; @observale price = 25; @computed get totalPrice () { return this.count * this.price } } ``` ```js @computed get getResult () { return this.count * 10 } {counter.getResult} ``` ### 禁止普通函数更改程序状态并引入action装饰器 ```js // configure action import { action , configure } from 'mobx'; // 通过配置强制程序使用action函数更改应用程序中的状态 configure({enforceActions: 'observed'}); @action.bound increment () { this.count = this.count + 1; } @action.bound decrement () { this.count = this.count - 1; } 只有action 函数才能更改状态 ``` ### Mobx 数据监测 5.2 autorun 方法 当监测的状态发生变化时, 你想根据状态产生 “效果”, 请使用 autorun, autorun 会在初始化的时候执行一次,会在每次状态发生变化时执行 ```js autotun (async () => { let response = await uniqueUsername(this.username); }, { delay, 1500}); import {autorun} from 'mobx' constructor () { autorun(() => { try { uniqueUsername(this.username) console.log('用户名可用') } catch (e) { console.log(e.message) } }, { delay: 2000 }) } function uniqueUsername(username) { return new Promise((reslove, reject) => { if (username === 'admin') { reject('用户名已存在') } else { reslove('用户名可用') } }) }
counter.changeUsername(e.target.value) } /> {counter.username}
```