在我的Meteor应用程序中,我尝试从此API加载随机图像,并且得到类似以下内容的JSON:

{
 "id":2026
 "url": "https:// ... " ,
 "large_url":null,
 "source_id":609,
 "copyright":"CC0",
 "site":"unsplash"
}


我这样做:

if (Meteor.isClient) {
    Template.body.helpers({
        randomImage: function() {
            Meteor.call("unImage", function(error, results) {
                Session.set('url', results.data.url);
            });
            return Session.get('url');
       }
    });
}

if (Meteor.isServer) {
    Meteor.methods({
        unImage: function() {
            this.unblock();
            return Meteor.http.call("GET", "http://www.splashbase.co/api/v1/images/random");
        }
    });
}


在我的html中:

<div class="header" style="background-image: url('{{randomImage}}')">
  ...
</div>


这是可行的,但是每秒或多或少会重新加载图像。我猜这是由于服务器端的unImage函数随服务器或类似的东西(不确定)一起加载而引起的。无论如何,我不能停止它。关于如何解决的任何想法?为什么会这样呢?

最佳答案

这是因为randomImage帮助器中的会话变量。
Session variables本质上是反应性的,只要更改其值,它就会在块中重新运行。

在这种情况下,辅助代码将一次又一次地重新运行,因此,Meteor方法将一次又一次地被调用

因此,将助手中的Meteor.call移至呈现的事件,如下所示

if (Meteor.isClient) {
    Template.body.rendered= function(){
       Meteor.call("unImage", function(error, results) {
          Session.set('url', results.data.url);
       });
    }


    Template.body.helpers({
        randomImage: function() {
            return Session.get('url');
       }
    });
}


一旦模板准备就绪并设置了url变量,哪个应该调用Meteor方法,从而以响应方式帮助助手randomImage重新运行并获得相同的值

10-04 23:05
查看更多