如何在 MobX 中的每一个可能的变化上运行react回调?

IT技术 reactjs mobx mobx-react
2022-07-09 00:27:16

这是我的简化商店:

export class ProfileStore {
  profile = {
    id: 1,
    name: "Tommy",
    todos: [
      {
        value: "Clean the room",
        done: false
      }
    ]
  };

  constructor() {
    makeObservable(this, {
      profile: observable,
    });
  }
}

我的目标是聆听可观察到的“配置文件”中的每一个可能的变化。我想reaction从 MobX 中使用它,但这有点棘手。

reaction(
      () => this.profile,
      () => {
        console.log("change");
      }
    );

上面的例子根本不起作用,因为 MobX 不响应值,而是响应属性和引用。所以我把它改成这样:

reaction(
      () => ({
        id: this.profile.id,
        name: this.profile.name,
        todos: this.profile.todos.slice()
      }),
      () => {
        console.log("change");
      }
    );

它开始工作,但并非完全正常。done除了在 todos 中切换属性之外,它还会监听每一个变化。如果我添加另一个属性,我需要在这里列出,这有点乏味。

处理这个问题的最佳方法是什么?如何应对每一个可能的变化?

我为此制作了一个代码框:链接

尝试按下按钮并查看计数器。

1个回答

要对每个可能的更改做出react,您需要取消引用每个属性。为此,例如,您可以使用toJS方法来序列化您的profile对象。(甚至本机JSON.stringify):

import { reaction, toJS } from 'mobx';

// ...

    reaction(
      () => toJS(profileStore.profile),
      () => {
        setReactionCounter((state) => state + 1);
      }
    );

代码沙盒