我正在尝试做什么...
我需要使用存储在用户 Meteor.user()
中的一些子属性对象,例如 Meteor.user().profile.preferences.preference_one
, Meteor.user().profile.preferences.preference_two
等等。这些子属性在响应式(Reactive)自动运行 block 中使用,因为必须在它们发生更改时进行重新计算。
我的问题是...
我发现,当我从 react block 中引用这些子属性的值时,任何 Meteor.user()
的更改都会触发自动运行。对象,包括不以任何方式影响我明确引用的数据的更改。例如,如果 Meteor.user().profile.name
更新,然后任何包含 Meteor.user().profile.preferences.preference_one
的自动运行或 Meteor.user().profile.preferences.preference_two
也被解雇了,因为他们都有一个共同的 parent 。
I have seen a similar question处理限制 Meteor 的 react 范围,但它处理自定义集合,而不是 Meteor.users
收藏。我看不出那里的解决方案如何适用,因为他们在订阅中指定字段以限制向客户端发布哪些子属性,在我的例子中,我需要 Meteor.user()
的所有子属性。 .但我需要能够选择我对哪些子属性使用react!
在本地存储子属性值,然后比较每个更改当然可行,但这是一种蛮力解决方案,因为它需要额外的逻辑,并且自动运行无论如何都会触发。
最佳答案
我不知道这是否是最佳方式,但请看一下这个例子:
Tracker.autorun(function() {
var user = Meteor.user();
if (user && user.profile)
Session.set('p1', user.profile.preference1);
});
Tracker.autorun(function() {
var p1 = Session.get('p1');
console.log("p1 is " + p1);
});
第一个 autorun
将在每次用户数据更改时触发,而第二个 autorun
仅在该特定属性更改时触发。
关于javascript - 使 Meteor 对 Meteor.user() 的特定子项有反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753641/