模板帮助程序在session.set之后未更新



此Meteor代码需要基于Session.get('headerLabel')更改headerLabel的值,当在不同的客户端文件中设置时,它不会更新模板显示。

为什么以及如何修复?感谢

// client/header.js
Template.header.helpers({
  headerLabel: function () {
    let userId = Meteor.userId();
    if (!userId) {
      Session.set('headerLabel', 'Please login');
    } else {
      Meteor.subscribe('headerLabel');
      let label = HeaderLabelCol.findOne({userId: userId}).headerLabel;
      Session.set('headerLabel', label);
    }
    return {headerLabel: Session.get('headerLabel')};
  }
});
// client/lib.js
utility = (function () {
  return {
    toast: function (headerMsg) {
      const temp = Session.get('headerLabel');
      Session.set('headerLabel', headerMsg);
      setTimeout(() => {Session.set('headerLabel', temp)}, 2000);
    }
  }
}());
<template name="header">
  <header>
    <h1 class="main-menu">
      <button class="mainMenu" type="button">&#9776;</button>
    </h1>
    <h3>
      <label class="header-label">
        {{headerLabel.headerLabel}}
      </label>
    </h3>
    <h1>
      <button class="subMenu" type="button">&#8942;</button>
    </h1>
  </header>
</template>

这是从客户端的其他文件中调用的utility.toast('Wrong entries');

Helper函数应该只获取模板所需的数据,而不应该操纵应用程序的状态。特别是,每次重新提交模板时,您调用的Meteor.subscribe都会创建一个新的订阅句柄。这是一个严重的泄漏。

相反,您应该将逻辑代码移动到onCreatedonRenderedonDestroyed方法。

Template.header.onCreated(function() {
  this.subscribe('headerLabel');
  this.autorun(function() {
    let userId = Meteor.userId();
    if (userId) {
      let label = HeaderLabelCol.findOne({userId: userId}).headerLabel;
      Session.set('headerLabel', label);
    } else {
      Session.set('headerLabel', 'Please login');
    }
  });
});
Template.header.helpers({
  headerLabel: function () {
    return Session.get('headerLabel');
  },
});

最新更新