如何解决Meteor 查询在服务器上运行得非常好,但在客户端
import { Meteor } from 'meteor/meteor';
const Animals = new Mongo.Collection("animals");
let animalsFindOne = Targets.findOne({animal: "henry"});
console.log(_.get(animalsFindOne,'food.favorite.amount'));
以及呈现到模板的 animals.js
文件
import {Template} from "meteor/templating";
import {Mongo} from "meteor/mongo";
import "/imports/ui/targets/animals.html";
const Animals = new Mongo.Collection("animals");
let animalsFindOne = Targets.findOne({animal: "henry"});
Template.targets.helpers({
foodamount: function() {
return _.get(animalsFindOne,'food.favorite.amount';
}
});
我可以将 "foo" 作为 foodamount 返回,模板会完美呈现它。对于 _.get
,我使用 erasaur:meteor-lodash
,它在 server.js
中运行良好。在服务器控制台中,输出为“5”,这是预期且很棒的输出。
我在这里遗漏了什么?
编辑:我也安装了自动发布,我不期待删除它,因为这个软件无论如何都是一个测试。
解决方法
animalsFindOne
已经在 foodAmount
助手之外定义,因此它不会触发模板的基于反应性的重绘机制。
为了在助手中获得反应性,您需要在助手中调用查询:
import {Template} from "meteor/templating";
import {Mongo} from "meteor/mongo";
import "/imports/ui/targets/animals.html";
const Animals = new Mongo.Collection("animals");
Template.targets.helpers({
foodAmount: function() {
let animalsFindOne = Targets.findOne({animal: "henry"});
return _.get(animalsFindOne,'food.favorite.amount';
}
});
编辑:Meteor 允许 optional chaining 使用更新的版本,所以这里不需要 lodash:
Template.targets.helpers({
foodAmount: function() {
let animalsFindOne = Targets.findOne({animal: "henry"});
return animalsFindOne?.food?.favorite?.amount
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。