mobx
:Simple, scalable state management
During the development process, we often have some attributes and methods that need to be used on multiple pages. We can use mobx not just for simple parent-child component transfers. I personally understand that it can be compared to vuex in vue. mobx is used relative to redux. It’s simpler and more convenient. Let’s talk about how to use it directly.
1 - Installation
React 绑定库: npm install mobx-react --save
2 - Configure store file
import {
observable, runInAction, makeAutoObservable } from "mobx";
class Normal {
//公共属性,或者可以理解为多页面需要使用的属性
singlePrice: number = 0.07;
doublePrice: number = 0.1;
order = {
};
isNeedPrint: boolean = false;
eqId: number = 1;
//更改属性的方法
changeSinglePrice(price: number) {
console.log("调用了");
this.singlePrice = price;
}
changeDoublePrice(price: number) {
this.doublePrice = price;
}
changeEq(id: number) {
this.eqId = id;
}
setOrder(item: any) {
this.order = item;
}
setNeedPrint(status: boolean) {
this.isNeedPrint = status;
}
clearOrder() {
this.order = {
};
}
//不要漏了这个
constructor() {
makeAutoObservable(this);
}
}
//导出 new 对象名
export default new Normal();
3-Use in the page
//引入mobx和store
import store from '../../store/store'
import {
observer } from 'mobx-react'
const Setting = () => {
const changeMachine = (value: string) => {
if (value == 1) {
//调用的就是store中更改eqid的方法
store.changeEq(1)
} else if (value == 2 {
store.changeEq(2)
}
}
//更改single
const changeSingle = (value: any) => {
//调用store中的方法
store.changeSinglePrice(value)
}
return (
<div className={
"mt-6"}>
<div className="flex items-center flex-row mt-5">
<div className="w-20">单面价格:</div>
//这里就是调用store中的属性store.singlePrice
<InputNumber placeholder={
store.singlePrice.toString()} className="w-100" onChange={
changeSingle} />
</div>
</div>
</div>
);
};
//!!!!重点!!!!! 一定要记得 observer 组件
export default observer(Setting);
Be sure to remember the last observer! !
In this way, you can use mobx for data management and storage, fighting everyone