如何解决当与 React 钩子一起使用时,Mobx 可观察字段不会在观察者UI中更新
我正在使用 mobx 商店创建一个带有 react-hooks 的简单 React 应用程序。我在这里使用的软件包是 mobx 和 mobx-react-lite。 当我点击添加/乘法按钮时,没有任何反应。更新的计数值没有反映。 我是否缺少要在某处添加的东西,我们需要支持 mobx? 代码的结构是这样的:
App.tsx =>
function App() {
return (
<div className="App">
<header>
Math
</header>
<hr />
<Multiplier />
<Adder />
<Square />
</div>
);
}
export default App;
Multiplier.tsx =>
import { observer } from "mobx-react-lite";
import { useCounterStore } from "../storeProvider/RootStoreProvider";
function Multiplier(){
const store = useCounterStore();
return(
<div>
<div>Count after multiplying by 5: {store.count}</div>
<button onClick={() => store.multiplyByFive()}>Multiply</button>
</div>
)
}
export default observer(Multiplier);
Adder.tsx =>
import { observer } from "mobx-react-lite";
import { useCounterStore } from "../storeProvider/RootStoreProvider";
function Adder(){
const store = useCounterStore();
return(
<div>
<div>Count after addition by 5: {store.count}</div>
<button onClick={() => store.addByFive()}>Add</button>
</div>
)
}
export default observer(Adder);
Square.tsx =>
import { observer } from "mobx-react-lite";
import { useCounterStore } from "../storeProvider/RootStoreProvider";
function Square(){
const store = useCounterStore();
return(
<div>Count square : {store.Squared}</div>
)
}
export default observer(Square);
useCounterStore 从此文件导出:
import { createContext,ReactNode,useContext } from "react";
import { RootStore } from "../store/Root";
let store: RootStore;
const RootStoreContext = createContext<RootStore | undefined>(undefined);
export function useRootStore() {
const context = useContext(RootStoreContext);
if (context === undefined) {
throw new Error("useRootStore must be used within RootStoreProvider");
}
return context;
}
export function useCounterStore() {
const { CounterStore } = useRootStore();
return CounterStore;
}
export function RootStoreProvider({ children }: { children: ReactNode }) {
const root = store ?? new RootStore();
return <RootStoreContext.Provider value={root}>{children}</RootStoreContext.Provider>
}
这个文件正在导出在 index.tsx 文件中使用的 RootStoreProvider =>
ReactDOM.render(
<RootStoreProvider>
<React.StrictMode>
<App />
</React.StrictMode>
</RootStoreProvider>,document.getElementById('root')
);
// If you want to start measuring performance in your app,pass a function
// to log results
reportWebVitals();
Edit1 (RootStore.ts):
import { Counter } from "./Counter";
export class RootStore{
public CounterStore:Counter;
constructor(){
this.CounterStore = new Counter();
}
}
Edit2 : CounterStore =>
import { action,computed,observable } from "mobx";
export class Counter{
@observable count = 0;
@action multiplyByFive(){
this.count = this.count * 5;
}
@action addByFive(){
this.count = this.count + 5;
}
@computed get Squared(){
return this.count * this.count;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。