当前位置:网站首页>Mobx knowledge point collection case (quick start)
Mobx knowledge point collection case (quick start)
2022-07-07 07:11:00 【Fat goose 68】
List of articles
One 、 Article reference
Two 、 Knowledge points in series
2.1 Concatenate using annotation
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({
// Mandatory requirements modify observable The data of , Make sure to put action in
enforceActions: 'observed',
});
// 1. initialization mobx Container warehouse
class MyStore {
@observable count = 0;
name = 'huangbiao';
@observable foo = 'bar';
@observable price = 10;
@action.bound increment() {
this.count++;
}
@computed get totalPrice() {
console.log('totalPrice This uses caching , Not how many times , Just how many times ');
return this.count * this.price;
}
// bound Express context this by Instance object , You cannot use arrow functions
@action.bound change() {
console.log(this);
this.foo = 'hello';
this.foo = 'world';
this.count = 10;
}
@action.bound asyncChange () {
setTimeout(() => {
// this.count = 100
// 1. Definition action function
// this.changeCount()
// 2. Call directly 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 By default, it will execute once * then , When the interior depends on observable The execution is triggered again when the data changes */
autorun(() => {
console.log('autorun: ', mystore.name, mystore.count, mystore.foo);
});
/****************** Modify multiple times observable Will cause multiple executions autorun function ******************** // If called twice in a row observable The data of , be autorun It will also be called twice , Low efficiency // mystore.foo = 'hello' // mystore.foo = 'world' // mystore.count = 10 // 1. The operation that will be modified many times In a action in // mystore.change() // 2. runInAction Create a one-time action. // runInAction(() => { // mystore.foo = 'hello'; // mystore.foo = 'world'; // mystore.count = 10; // }) */
// const tempChnage = mystore.change
// The context is no longer store Object , So you need to use @action.bound Guarantee context
// tempChnage()
/****************** Problems caused by asynchronous triggering ******************** */
// mystore.asyncChange()
/****************** when ******************** // When count > 100 When , Execute custom logic only once when( () => { return mystore.count > 100 }, () => { console.log('when -> ', mystore.count) } ) mystore.changeCount(200) // when Meeting the condition only triggers once mystore.changeCount(300) */
/****************** Problems caused by asynchronous triggering ******************** */
reaction(
() => {
return mystore.count
},
(data, reaction) => {
console.log('reaction -> ', data)
// Manually stop the current reaction Listening in
if (data > 3) {
reaction.dispose()
}
}
)
// 2. Use in components mobx Container state
@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> The total price :{
store.totalPrice}</div>
<div> The total price :{
store.totalPrice}</div>
<div> The total price :{
store.totalPrice}</div>
<div> The total price :{
store.totalPrice}</div>
<div> The total price :{
store.totalPrice}</div>
<div> The total price :{
store.totalPrice}</div>
<div> The total price :{
store.totalPrice}</div>
</>
);
}
}
// 3. Initiate... In the component action Modify the state of the container
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 Using functions
import {
observable, autorun, action} from "mobx";
var person = observable({
// observable attribute :
name: "John",
age: 42,
showAge: false,
// Compute properties :
get labelText() {
return this.showAge ? `${
this.name} (age: ${
this.age})` : this.name;
},
// action :
setAge(age) {
console.log('setAge')
this.age = age;
}
}, {
setAge: action
});
// person It's actually a proxy object
console.log('person', person)
// Object properties are not exposed 'observe' Method ,
// But don't worry , 'mobx.autorun' More powerful
autorun(() => {
console.log(person.labelText)
});
person.name = "Dave";
// Output : 'Dave'
person.showAge = true
person.setAge(21);
// wait
边栏推荐
- libcurl返回curlcode说明
- Composition API 前提
- readonly 只读
- How to share the same storage among multiple kubernetes clusters
- From zero to one, I will teach you to build the "clip search by text" search service (2): 5 minutes to realize the prototype
- $parent(获取父组件) 和 $root(获取根组件)
- Stack Title: nesting depth of valid parentheses
- sqlserver多线程查询问题
- Matlab tips (29) polynomial fitting plotfit
- 工具类:对象转map 驼峰转下划线 下划线转驼峰
猜你喜欢
CompletableFuture使用详解
$refs: get the element object or sub component instance in the component:
.net 5 FluentFTP连接FTP失败问题:This operation is only allowed using a successfully authenticated context
Special behavior of main function in import statement
弹性布局(二)
MOS管参数μCox得到的一种方法
transform-origin属性详解
Answer to the second stage of the assignment of "information security management and evaluation" of the higher vocational group of the 2018 Jiangsu Vocational College skills competition
2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书
2018 Jiangsu Vocational College skills competition vocational group "information security management and evaluation" competition assignment
随机推荐
Select the product attribute pop-up box to pop up the animation effect from the bottom
Reflection (II)
Maze games based on JS
FPGA course: application scenario of jesd204b (dry goods sharing)
The latest trends of data asset management and data security at home and abroad
Readonly read only
js小练习----分时提醒问候、表单密码显示隐藏效果、文本框焦点事件、关闭广告
From zero to one, I will teach you to build the "clip search by text" search service (2): 5 minutes to realize the prototype
Jetpack compose is much more than a UI framework~
Distributed ID solution
After the promotion, sales volume and flow are both. Is it really easy to relax?
. Net core accesses uncommon static file types (MIME types)
Test of transform parameters of impdp
【JDBC以及内部类的讲解】
Multithreading and high concurrency (9) -- other synchronization components of AQS (semaphore, reentrantreadwritelock, exchanger)
Esxi attaching mobile (Mechanical) hard disk detailed tutorial
How to share the same storage among multiple kubernetes clusters
.net core 访问不常见的静态文件类型(MIME 类型)
Algorithm --- bit count (kotlin)
SQLMAP使用教程(四)实战技巧三之绕过防火墙