当前位置:网站首页>mobx 知识点集合案例(快速入门)
mobx 知识点集合案例(快速入门)
2022-07-07 02:06:00 【胖鹅68】
一、文章参考
二、知识点串联
2.1 使用注解方式串联
import React, {
Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
// import App from './App';
import * as serviceWorker from './serviceWorker';
import {
BrowserRouter } from 'react-router-dom';
import {
observable, action, autorun, computed, configure, runInAction, when, reaction } from 'mobx';
import {
observer } from 'mobx-react';
import store from './mobx/AppStore';
configure({
// 强制要求 修改 observable 的数据,一定要放到 action 中
enforceActions: 'observed',
});
// 1. 初始化 mobx 容器仓库
class MyStore {
@observable count = 0;
name = 'huangbiao';
@observable foo = 'bar';
@observable price = 10;
@action.bound increment() {
this.count++;
}
@computed get totalPrice() {
console.log('totalPrice 这里使用了缓存,不是展示多少次,就调用多少次');
return this.count * this.price;
}
// bound 表示上下文 this 为 实例对象,不能使用箭头函数
@action.bound change() {
console.log(this);
this.foo = 'hello';
this.foo = 'world';
this.count = 10;
}
@action.bound asyncChange () {
setTimeout(() => {
// this.count = 100
// 1. 定义 action 函数
// this.changeCount()
// 2. 直接调用action
// action('changeFoo', () => {
// this.count = 30
// })()
// 3. runInAction
runInAction(() => {
this.count = 40
})
}, 200)
}
@action.bound changeCount(value = 20) {
this.count = value
}
}
const mystore = new MyStore();
/** * auto 默认会执行一次 * 然后,当内部所依赖的 observable 数据发生改变的时候重新触发执行 */
autorun(() => {
console.log('autorun: ', mystore.name, mystore.count, mystore.foo);
});
/****************** 修改多次observable会引发多次执行 autorun 函数 ******************** // 如果连续调用两次 observable 的数据,则 autorun 也会调用两次,效率比较低 // mystore.foo = 'hello' // mystore.foo = 'world' // mystore.count = 10 // 1. 将多次修改的操作 放到一个 action 中 // mystore.change() // 2. runInAction 创建一个被立即调用的一次性 action。 // runInAction(() => { // mystore.foo = 'hello'; // mystore.foo = 'world'; // mystore.count = 10; // }) */
// const tempChnage = mystore.change
// 上下文已经不是 store对象了,因此需要使用 @action.bound 保证上下文
// tempChnage()
/****************** 异步触发会引发的问题 ******************** */
// mystore.asyncChange()
/****************** when ******************** // 当 count > 100 的时候,只执行一次自定义逻辑 when( () => { return mystore.count > 100 }, () => { console.log('when -> ', mystore.count) } ) mystore.changeCount(200) // when 满足条件只触发了一次 mystore.changeCount(300) */
/****************** 异步触发会引发的问题 ******************** */
reaction(
() => {
return mystore.count
},
(data, reaction) => {
console.log('reaction -> ', data)
// 手动停止当前 reaction 的监听
if (data > 3) {
reaction.dispose()
}
}
)
// 2. 在组件中使用 mobx 容器的状态
@observer
class App extends Component {
render() {
const {
store } = this.props;
return (
<>
<div>AppMobx</div>
<div>{
store.count}</div>
<div>
<button onClick={
store.increment}>increment</button>
</div>
<div>总价:{
store.totalPrice}</div>
<div>总价:{
store.totalPrice}</div>
<div>总价:{
store.totalPrice}</div>
<div>总价:{
store.totalPrice}</div>
<div>总价:{
store.totalPrice}</div>
<div>总价:{
store.totalPrice}</div>
<div>总价:{
store.totalPrice}</div>
</>
);
}
}
// 3. 在组件中发起 action 修改容器的状态
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
{
/* <App/> */}
<App store={
mystore} />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
2.2 使用函数
import {
observable, autorun, action} from "mobx";
var person = observable({
// observable 属性:
name: "John",
age: 42,
showAge: false,
// 计算属性:
get labelText() {
return this.showAge ? `${
this.name} (age: ${
this.age})` : this.name;
},
// 动作:
setAge(age) {
console.log('setAge')
this.age = age;
}
}, {
setAge: action
});
// person 实际上是一个 proxy 对象
console.log('person', person)
// 对象属性没有暴露 'observe' 方法,
// 但不用担心, 'mobx.autorun' 功能更加强大
autorun(() => {
console.log(person.labelText)
});
person.name = "Dave";
// 输出: 'Dave'
person.showAge = true
person.setAge(21);
// 等等
边栏推荐
- Install mongodb database
- MySQL卸载文档-Windows版
- Swagger3 configuration
- 哈趣投影黑馬之姿,僅用半年强勢突圍千元投影儀市場!
- A program lets you understand what static inner classes, local inner classes, and anonymous inner classes are
- Ha Qu projection dark horse posture, only half a year to break through the 1000 yuan projector market!
- Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
- c语言(结构体)定义一个User结构体,含以下字段:
- C语言整理(待更新)
- You don't know the complete collection of recruitment slang of Internet companies
猜你喜欢
tkinter窗口选择pcd文件并显示点云(open3d)
Rk3399 platform development series explanation (WiFi) 5.52. Introduction to WiFi framework composition
window下面如何安装swoole
You don't know the complete collection of recruitment slang of Internet companies
uniapp开发小程序如何使用微信云托管或云函数进行云开发
雷特智能家居龙海祁:从专业调光到全宅智能,20年专注成就专业
Software testing knowledge reserve: how much do you know about the basic knowledge of "login security"?
Several key steps of software testing, you need to know
地质学类比较有名的外文期刊有哪些?
HKUST & MsrA new research: on image to image conversion, fine tuning is all you need
随机推荐
Database notes 04
QT console output in GUI applications- Console output in a Qt GUI app?
Handling hardfault in RT thread
谷歌 Chrome 浏览器发布 103.0.5060.114 补丁修复 0-day 漏洞
Basic DOS commands
Go straight to the 2022ecdc fluorite cloud Developer Conference: work with thousands of industries to accelerate intelligent upgrading
ICML 2022 | explore the best architecture and training method of language model
Three updates to build applications for different types of devices | 2022 i/o key review
You don't know the complete collection of recruitment slang of Internet companies
学习笔记|数据小白使用DataEase制作数据大屏
港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need
Experience sharing of contribution of "management world"
c语言(结构体)定义一个User结构体,含以下字段:
基本Dos命令
一段程序让你明白什么静态内部类,局部内部类,匿名内部类
JMeter function assistant - random value, random string, fixed value random extraction
C language (structure) defines a user structure with the following fields:
How to solve sqlstate[hy000]: General error: 1364 field 'xxxxx' doesn't have a default value error
Jcmd of JVM command: multifunctional command line
ETCD数据库源码分析——从raftNode的start函数说起