【发布时间】:2021-04-24 04:34:39
【问题描述】:
我刚开始使用 MobX,如果我在这里遗漏了一些非常琐碎的东西,请原谅我。为了让我的脚湿透,我刚刚构建了一个使用上下文的简单加减项目。我制作了 3 个组件 AddButton、SubtractButton 和 Answer。所有读取和更新使用 observable 的类的实例。
代码沙盒:https://codesandbox.io/s/stoic-chandrasekhar-kz5e9?file=/src/App.tsx
目的是在 AnswerStore 更改时更新 Answer 组件。 (答案包裹在观察者HOC中)
这就是商店的样子
export class AnswerStore {
@observable
answer = 0;
@action
add() {
console.log("Adding 1 to ", this.answer);
this.answer = this.answer + 1;
}
@action
sub() {
console.log("Subtracting 1 from ", this.answer);
this.answer = this.answer - 1;
}
}
const context = React.createContext({} as AnswerStore);
export const useStore = () => React.useContext(context);
Answer 组件如下所示
import { observer } from "mobx-react-lite";
import React from "react";
import { useStore } from "./store";
const answer = observer(() => {
const store = useStore()
return <h1>Answer is: {store.answer}</h1>;
})
export default answer
再次,我不确定我在这里缺少什么:/
【问题讨论】:
标签: reactjs mobx mobx-react