【问题标题】:React component not updating when the MobX object updatesMobX 对象更新时 React 组件不更新
【发布时间】: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


【解决方案1】:

const context = React.createContext({} as AnswerStore);

“as”语句是 Typescript,它表示{} 应该被视为什么类型。

只存在于Typescript中,因为Typescript类型在编译后生成的Javascript中不存在。所以上下文是用一个普通的空对象初始化的,而不是一个 observable。

如果你这样做

const context = React.createContext(new AnswerStore());

那么据我所知,它应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多