gpt4 book ai didi

reactjs - 如何对 MobX 中每个可能的变化运行 react 回调?

转载 作者:行者123 更新时间:2023-12-02 02:00:02 24 4
gpt4 key购买 nike

这是我的简化商店:

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

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

我的目标是倾听可观察到的“个人资料”内的每一个可能的变化。我想使用 MobX 的 reaction 来实现此目的,但这有点棘手。

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

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

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

它开始起作用,但并不完全起作用。除了切换 todos 中的 done 属性之外,它还会监听所有更改。如果我添加另一个属性,我需要在这里列出,这有点乏味。

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

我为此制作了一个codesandbox:link

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

最佳答案

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

import { reaction, toJS } from 'mobx';

// ...

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

Codesandbox

关于reactjs - 如何对 MobX 中每个可能的变化运行 react 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69099041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com