【问题标题】:If() block changing the Meteor data receivedIf() 块改变接收到的 Meteor 数据
【发布时间】:2016-05-01 18:40:50
【问题描述】:

好的。我无语。两天前我遇到了这种奇怪的行为,我真的不知道发生了什么。

在我的代码中:

character: Characters.find({
    'user._id': Meteor.userId(),
    'gameId': this.props.gameId
}).fetch(),

它在 getMeteorData 函数内部(我使用 Meteor 和 React),mixin [ReactMeteorData] 也存在。

现在在componentWillMount() 函数中,我有这段代码。我要做的是检查这个用户和这个游戏里面是否有一个角色。

componentDidMount: function() {
    console.log(this.data.character);
}

它返回 [Class] 以及我正在寻找的字符。伟大的!所以现在我添加这段代码,它看起来像这样:

componentDidMount: function() {
    console.log(this.data.character);

    if (this.data.character.length > 0) {
        console.log('yay!');
    } else {
        console.log('nay...');
    }
}

所以这是一个正常的、毫无疑问的if()。猜猜我从第一个console.log()[] 得到什么。为什么?为什么这个if 改变了我从数据库中获得的信息?!

【问题讨论】:

  • 我没有看到条件块更改任何值。我看到一个空数组。您确定 this.data.character 已加载并正确分配吗?你真的有数据库条目吗?
  • 是的。正如我所说,没有if() 块,我会得到一个[Class],其中有我想要的对象。我开始怀疑这可能与订阅以及它们加载所需的时间有关。
  • 对不起。不明白。是的,竞争条件在这里可能是一个问题(特别是对于流星/节点非阻塞数据库 io)。您可以为Characters.find(..)(..).fetch() 分配任何回调来处理您的数据吗?
  • Meteor 在“技术上”是同步的。我认为这是不可能的。
  • 好的。我对流星不熟悉。

标签: javascript mongodb meteor reactjs


【解决方案1】:

问题是,当我尝试使用订阅时,它们还没有准备好。我所做的是重写订阅的方式。我将它从路由器(因此没有订阅)移动到组件本身。像这样:

data = {}
subs = {}

subs.something = Meteor.subscribe("something", argument);

if (subs.something.ready()) {
    data.something = Somethings.find({}).fetch();
    // the same query I use in publish method but with .fetch()
    // because otherwise Meteor throws a warning
}

这是转到getMeteorData 函数的代码。然后在render() 中,我可以像这样使用这些订阅:

render: function() {
    return(
        <p>{this.data.something ? this.data.something.property : 'Loading...'}</p>
    );
}

然后它工作得非常好。我已经重写了所有组件以使用这种处理方式,现在我在订阅方面没有任何问题。它也感觉更加“组件化”和“反应性”,因为包括订阅在内的所有内容都包含在父组件中,并且相关数据正在通过 props 传递给子组件。无需在路由器中寻找代码和订阅方法。

【讨论】:

    猜你喜欢
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多