汽车和反应之间有什么明显的差异以及何时使用哪个?

发布于 2025-01-29 17:19:13 字数 754 浏览 3 评论 0原文

autorun反应之间有什么区别?我正在寻找一个完整的解释,有助于决定何时使用哪个。 反应是否有可能触发autorun没有触发?它们之间的关系如何?

这两个都一样吗?

autorun(() => {
  localStorage.setItem("current_order", JSON.stringify(this.currentOrder)) 
})
reaction(
  () => JSON.stringify(this.currentOrder),
  (json) => { 
    localStorage.setItem("current_order", json) 
  }
)

据我所知,反应的第一个参数将评估和检查更改,因此对于计算值来说是需要的,但如果< autorun 不应工作,只要<<<代码> this.currentorder 可观察到吗? json.stringify(this.currentorder) in reaction运行,即使this.currentorder是可观察到的,并且尚未更改?

What is the difference between autorun and reaction? I'm looking for a full explanation that helps to decide when to use which. Is it possible that reaction can even trigger while autorun does not? How they are related to each other?

Are these both the same?

autorun(() => {
  localStorage.setItem("current_order", JSON.stringify(this.currentOrder)) 
})
reaction(
  () => JSON.stringify(this.currentOrder),
  (json) => { 
    localStorage.setItem("current_order", json) 
  }
)

As far as I know, the first parameter of reaction will evaluate and check for changes, so it is desired for computed values, but shouldn't autorun just work fine if this.currentOrder is observable? Will JSON.stringify(this.currentOrder) in reaction run, even when this.currentOrder is observable and has not changed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

写给空气的情书 2025-02-05 17:19:13

autorun在初始化后立即运行,Rection仅在初始化后数据表达式更改后运行。

另外,由于反应仅在数据表达式更改时运行IT,这意味着反应给出了更多细粒度控制。

编辑:

添加一个示例以使其更清楚地

考虑此示例,您有两个可观察到的A和B,并且想在更改时使用B进行操作,但在B更改时不想做任何事情。如果您只制作autorun它将在任何观察值更改时运行,因此这不是您想要的。但是,使用反应,只能对A的更改做出反应(仅使用in表达函数)。

autorun runs immediately after it was initialised, reaction runs only after the data expression has changed after initialisation.

Also, because reaction runs only when data expression changes you can use other observables in the effect function, which would not work for autorun because it subscribes for all observables you use inside of it, which means reaction gives more fine grained control.

EDIT:

Adding an example to make it more clear

Consider this example, you have two observables A and B, and want to do something with B when A changes, but don't want to do anything when B changes. If you just make autorun it will run when any of the observables changes, so it's not what you want. But with reaction it's possible to only react to the changes of A (by only using A in expression function).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文