我有一个基于异步信息的模板,因此我使用 Session
数据以便在数据到达时以 react 方式呈现 View 。像这样的东西:
item.html:
<template name="item">
{{#with item}}
{{itemInformation.name}}
{{/with}}
</template>
item.js
Template.item.created = function () {
getItemData(this.data.item.id, function(data) {
Session.set("itemInformation", data);
});
}
Template.item.helpers({
itemInformation: function() {
return Session.get("itemInformation");
}
});
如果我有一个项目模板处于事件状态,这种方法似乎效果很好。但如果我在 #each
循环中使用这种方法,我就会遇到 session 数据冲突。
- 有我可以使用的“本地”
Session
数据吗? - 基于
#each
循环中的异步数据重新渲染 View 的正确方法是什么?
最佳答案
- 您可以在 onCreated 模板回调 (
self.localSession = new ReactiveDict ()
) 中创建一个 ReactiveDict( https://atmospherejs.com/meteor/reactive-dict - Session 实际上在其实现中使用它),并使用它代替 Session (self.localSession.set('itemInformation', data)
)。 您可以通过以下方式在模板助手中访问它:Template.instance().localSession.get('itemInformation')
。
如果您只想在字典中存储一项,您也可以以相同的方式使用单个 ReactiveVar ( https://atmospherejs.com/meteor/reactive-var )。
- 正如您所注意到的,您需要在某些 react 源中设置异步内容,您可以使用我上面描述的构造。
您的代码:
Template.item.created = function () {
var self = this;
self.localSession = new ReactiveDict ();
getItemData(self.data.item.id}, function(data) {
self.localSession.set("itemInformation", data);
});
}
Template.item.helpers({
itemInformation: function() {
return Template.instance().localSession.get("itemInformation");
}
});
关于javascript - Meteor #each 和 session 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34851993/