【问题标题】:Wait for data on Blaze when using ReactiveVar on Meteor在 Meteor 上使用 ReactiveVar 时等待 Blaze 上的数据
【发布时间】:2017-10-25 04:52:07
【问题描述】:

我在 Meteor.js 中的 Blaze 模板上遇到了一个奇怪的问题。以下模板被渲染四次(使用{{#each}} 运算符)

<template name="circle">
  <div class="col-md-6">
    <div class="circle-container">
      <div class="circle {{option}}" style="border: 9px solid {{color}}">
        <div class="circle-text {{option}}" style="color:{{color}}">{{name}}</div>
      </div>
    </div>
  </div>
</template>

数据作为包含对象数组的 ReactiveVar 传递给模板。每个对象在模板上呈现一个圆圈。生成此数据的逻辑如下:

const colorSet = ['red','gold','blue','green','orange','turquoise','wheat','fuchsia','purple'];
const colorNames = ['VERMELHO','AMARELO','AZUL','VERDE','LARANJA','TURQUESA','BEGE','ROSA','ROXO'];

var limit = colorSet.length;

// helper functions
function getRandomPosition() {
  return Math.floor(Math.random() * (limit + 1));
}

function getRightColor() {
  let position = getRandomPosition();
  let rightColor = {
    color: colorSet[position],
    name: colorNames[position],
    right: 'right-option',
  };
  return rightColor;
}

function getWrongColor() {
  let position1 = getRandomPosition();
  let position2 = getRandomPosition();
  while (position1 === position2) {
    position2 = getRandomPosition();
  }
  let wrongColor = {
    color: colorSet[position1],
    name: colorNames[position2]
  };
  return wrongColor;
}

function make4Circles() {
  let circles = [];
  circles.push(getRightColor());

  for (let i = 0; i < 3; i++) {
    circles.push(getWrongColor());
  }
  console.log('circles:', circles)
  return circles
}

////
// TEMPLATE HELPERS
///
Template.gameArea.onCreated(function () {
  this.circleArray = new ReactiveVar(make4Circles());
})


Template.gameArea.helpers({
  circles () => {
    return Template.instance().circleArray.get();
  }
})

问题是页面有时缺少数据,这给我的印象是模板在数据准备好之前就被渲染了。由于 blaze 是反应性的,我认为这不会发生,因为跟踪器会知道数据已更改并会再次重新渲染模板。但事实是,有时它缺少一些数据。

我查看了所有文档,但不确定我是否遇到了某种错误或做错了什么......

如果有人想运行代码,可以在这个 github repo 上:https://github.com/kemelzaidan

【问题讨论】:

    标签: javascript meteor meteor-blaze


    【解决方案1】:

    我怀疑问题不是来自 Blaze,而是来自您的数据生成算法。

    您的console.log('circles:', circles) 是否总是输出正确的数据?

    Math.floor(Math.random() * (limit + 1)) 似乎有时会在您的数组索引范围之外生成一个整数

    在您的情况下,limit 将是 9(即您的 colorSet 数组中有 9 个项目,因此索引从 0 到 8),所以 limit + 1 是 10。

    然后Math.floor 上的Math.random() * 10 有时会给出 9,这超出了您的数组范围。

    => 只需删除 +1 即可解决您的问题。

    【讨论】:

    • 谢谢@ghybs!如此愚蠢的错误……但有时当我们独自做事时,我们就是无法发现如此简单而小的错误。
    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2017-01-03
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2018-11-05
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多