一文快速上手 mobx!
派生状态
根据现有状态衍生出来的状态
mobx:核心库
mobx-react-lite:函数组件
mobx-react:函数组件和类组件
安装:yarn add mobx@6.3.1 mobx-react-lite
import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react-lite";
import React, { memo } from "react";
class User {
// 状态(成员属性)
name = "张三";
age = 18;
constructor() {
// 将这个对象转变为一个可以被观察的实例对象(自动绑定所有)
makeAutoObservable(this,{},{autoBind:true});
// 只绑定指定的的组件对象
// makeAutoObservable(this, {
// tBanners: observable,
// })
}
// 计算出生年份
get bornYear() {
return new Date().getFullYear() -18
}
// 动作(成员方法)
changeName(newName) {
this.name = newName;
}
increment() {
this.age += 1;
}
decrement() {
this.age -= 1;
}
}
// 得到一个可以被观察的实例对象
const user = new User();
// 创建一个有观察能力的组件
const MyComponent = observer(({ store }) => {
const {name,age,increment,decrement,bornYear} = store
return (
<>
<h2>
name:{name} age:{age} bornYear:{bornYear}
</h2>
<button onClick={()=>increment()}>+1</button>
<button onClick={()=>decrement()}>-1</button>
</>
);
});
const Mobx = memo(() => {
return (
<div>
<MyComponent store={user} />
</div>
);
});
export default Mobx;
import { makeAutoObservable } from "mobx";
class User {
// 状态(成员属性)
name = "张三";
age = 18;
constructor() {
// 将这个对象转变为一个可以被观察的实例对象
makeAutoObservable(this,{},{autoBind:true});
}
// 计算出生年份
get bornYear() {
return new Date().getFullYear() -18
}
// 动作(成员方法)
changeName(newName) {
this.name = newName;
}
increment() {
this.age += 1;
}
decrement() {
this.age -= 1;
}
}
export default User
import User from './User'
import Goods from './Goods'
//1. 合并
class RootStore{
constructor(){
this.user = new User()
this.goods = new Goods()
}
}
const rootStore = new RootStore()
//2. 创建上下文对象。并且封装成一个组件
const RootStoreContext = createContext()
const RootStoreProvider = ({children})=>{
return(
<RootStoreContext.Provider value = {rootStore} >
{chldren}
</RootStoreContext.Provider>
)
}
export default RootStoreProvider
// 3. 获取一个获取上下文对象数据的方法
export const useRootStore = ()=>{
return useContext(RootStoreContext)
}
<RootStoreProvider >
<App />
</RootStoreProvider>
import { observer } from "mobx-react-lite";
import {useRootStore} from './store'
const MyComponent = observer(() => {
const {user} = useRootStore()
const {name,age,increment,decrement,bornYear} = user
return (
<>
<h2>
name:{name} age:{age} bornYear:{bornYear}
</h2>
<button onClick={()=>increment()}>+1</button>
<button onClick={()=>decrement()}>-1</button>
</>
);
});