yarn add mobx mobx-react
npm i mobx mobx-react
使用class 来定义store , 注意使用计算属性的时候需要引入computed ,并且在constructor中 调用makeAutoObservable
// count.ts
import { computed, makeAutoObservable } from "mobx";
interface dataType {
age: number;
img: string;
name: string;
}
class CounterStore {
count = 0; // 定义数据
datalist: Array<dataType> = [];
constructor() {
makeAutoObservable(this, {
getDoubleCOunt: computed,
});
}
// 定义修改数据的方法
addCount = (data: number) => {
this.count += data;
};
get getDoubleCOunt() {
return this.count * 2;
}
async asyncFun() {
const res = await fetch(
"https://www.fastmock.site/mock/6405986d1d74fb37597d8fbd15da76e7/demo/getlist"
);
const data = await res.json();
this.datalist = data.data.list;
}
}
const counter = new CounterStore();
export default counter;
// main.ts
// 像react-redux一样,mobx-react 一样提供Provider 来 传递数据
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "mobx-react";
import CountStore from "./store/count";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<Provider store={CountStore}>
<App />
</Provider>
</React.StrictMode>
);
//App.tsx
import { useState } from "react";
import { inject, observer } from "mobx-react";
function App(props: any) {
console.log("props", props.store.count);
const clicks = () => {
props.store.add();
};
const getdata = async () => {
let data = await props.store.getdata();
console.log("data", data);
};
return (
<div className='App'>
<p>count:{props.store.count}</p>
<p>doublecount:{props.store.doubleCount}</p>
<button onClick={clicks}>+</button>
<button onClick={getdata}>getData</button>
</div>
);
}
export default inject("store")(observer(App));
import React from 'react'
import counter from './counterStore'
import task from './taskStore'
class RootStore {
constructor() {
this.counterStore = counter
this.taskStore = task
}
}
const rootStore = new RootStore()
// context机制的数据查找链 Provider如果找不到 就找createContext方法执行时传入的参数
const context = React.createContext(rootStore)
const useStore = () => React.useContext(context)
export { useStore }