这里是我的问题:流星JS:如何防止使用Meteor.call插入集合时的双重渲染?
在一个模板事件处理程序,我使用Meteor.call()
调用一个方法来将文档插入集合。
由于某些原因,这会导致关联的模板呈现两次而不是一次。如果我在事件处理程序中直接使用Collection.insert()
,则该模板只会呈现一次。我很困惑它为什么会渲染两次。数据更改时,如何防止模板呈现两次?
这里是我的代码:
Posts = new Meteor.Collection('posts');
if (Meteor.isClient) {
Template.postItem.rendered = function(e){
console.log("This was rendered");
}
Template.postsList.helpers({
posts: function() {
return Posts.find();
}
});
Template.postsList.events({
'submit form' : function (e) {
e.preventDefault();
var post = {
title: $(e.target).find('[name=title]').val(),
}
// This causes double render
Meteor.call('post', post, function(error, id){
if (error) {
console.log(error);
}
});
// This causes only a single render
//Posts.insert(post);
}
});
}
Meteor.methods({
post: function(attrs) {
return Posts.insert(attrs);
}
});
哦,孩子,这是令人沮丧的。我刚刚尝试了提前生成ID作为发送哈希的一部分的建议。这种工作,直到我做一些事情,如在服务器上添加一个时间戳文件,如'submit:new Date()。getTime()'。然后它会再次渲染两次。 “随机盐”是什么意思? – Chanpory
@Chanpory我的意思是: 1.我的方法有额外的参数'randomSeed'(它是可选的,btw) 2.然后,在它创建要插入的对象之后,它通过以下代码行生成id: var id = Random.create([user._id,text,randomSeed]).id(); 3.然后它对集合执行“插入”操作。你可以尝试'upsert' - 不知道 方法存根内有什么区别。 – yeputons
这个问题有没有更新? –