问题描述
据我所知,在基本级别使用ReactiveVar和Session变量之间的区别在于本地变量和全局变量。 ReactiveDict就像一个本地Session对象。
I understand that the difference between using ReactiveVar and Session variables is, at the basic level, a matter of local vs global variables. ReactiveDict is like a local Session object.
但是如果你已经在使用ReactiveVar,为什么要使用ReactiveDict呢? ReactiveDict似乎没有任何优于ReactiveVar的优势
But why use ReactiveDict at all if you're already using ReactiveVar? ReactiveDict doesn't seem to have any advantages over ReactiveVar
推荐答案
以下是 ReactiveDict (RD)和
ReactiveVar
(RV):
- 顾名思义,RD提供类似字典的语义:
set
获取一个键/值对,它有delete
和清除
方法。最重要的是它允许您将反应数据集中到一个变量中。坦率地说,这在大多数用例中都不是那么有趣,但请继续阅读。 - RD有一个
所有
方法,它返回所有键/值对中的每一个都注册了一个反应依赖关系。主要的好处是,如果你有一组相关的被动数据,你可以在字典的任何部分发生变化时触发autorun
。要使用一组RV执行此操作,您需要在每个RV上调用get
。 - 如果您传递名称进入RD构造函数,它将在热代码推送中存活下来。事实上,实际上只是一个RD。
- As its name implies, RD offers dictionary-like semantics:
set
takes a key/value pair and it hasdelete
andclear
methods. The bottom line is it lets you cluster reactive data into a single variable. Frankly, this isn't all that interesting in most use cases, but keep reading. - RD has an
all
method which returns all of the key/value pairs and registers a reactive dependency on each of them. The main benefit is that if you have a cluster of related reactive data you can fire anautorun
whenever any part of the dictionary changes. To do this with a set of RVs, you'd need to callget
on each of them. - If you pass a name into the RD constructor, it will survive a hot code push. In fact, Session is actually just an RD.
在实践中,我发现了RD的一些用例,但在大多数情况下你都可以选择RV。
In practice, I've found a few use cases for RDs, but RVs are what you'll likely choose in most situations.
推荐阅读: ReactiveDict
这篇关于Meteor:ReactiveVar vs ReactiveDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!