汽车和反应之间有什么明显的差异以及何时使用哪个?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 forautorun
because it subscribes for all observables you use inside of it, which meansreaction
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 withreaction
it's possible to only react to the changes of A (by only using A in expression function).