我只是尝试Meteor而且我在Javascript中一般都不是很先进。我正在尝试使用模板从客户端的集合中显示对象的text属性,但是我得到了标题中提到的错误。我刚刚修改了默认的Meteor基础项目。
main.html中:
<head>
<title>Test</title>
</head>
<body>
<section>
{{> tweet}}
</section>
</body>
<template name="tweet">
<h1 class="mt-5">{{text}}</h1>
</template>
main.js
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';
import 'bootstrap/dist/js/bootstrap.bundle';
Tweets = new Mongo.Collection('tweets');
Template.tweet.onCreated(function tweetOnCreated() {
var txt = Tweets.findOne().text;
this.text = new ReactiveVar(txt);
});
Template.tweet.helpers({
text() {
return Template.instance().text.get();
},
});
var txt = Tweets.findOne().text;
有什么问题?我在这里对Javascript有一般性的误解,或者这个错误与Meteor如何工作有某种关系?
这与Meteor的工作原理有关。
当客户端启动时,它还没有任何数据。然后,客户端打开与服务器的订阅(假设您仍然安装了默认的自动发布包,这是为您完成的),之后不久将通过数据发送。
这是“不久之后”的一部分,这就是问题所在。
在你的情况下,这意味着当Tweets.findOne()
运行时,它还没有数据,因此没有文件可以从中读取text
。因此错误。通过检查文档是否返回来防止错误:
Template.tweet.onCreated(function () {
var doc = Tweets.findOne();
if (doc) {
this.text = new ReactiveVar(doc.text);
}
});
如果您尝试这样做,错误将消失,但仍然没有文本呈现。
所以现在我们希望在数据可用时再次运行该部分代码。 Blaze在助手中自动执行此操作,但在其他任何地方您需要将其包装在autorun
中:
Template.tweet.onCreated(function () {
this.text = new ReactiveVar();
this.autorun(() => {
var doc = Tweets.findOne();
if (doc) {
this.text.set(doc.text);
}
});
});
我还将反应变量的创建移出了自动运行,因为我们只想创建一次然后设置或获取它的值。
或者,我之前提到助手会自动自动运行。这意味着您可以在帮助程序中找到推文以简化模板:
Template.tweet.helpers({
text() {
var doc = Tweets.findOne();
if (doc) return doc.text;
},
});
更好的是,我们不再需要ReactiveVar
了,可以删除整个onCreated
功能!