【发布时间】:2016-05-26 19:10:53
【问题描述】:
我正在使用 React.js 和 Meteor.js,并尝试在 React 中使用 Meteor 的 subscribe,基于我正在阅读的 a blog post。我在这里的想法,如果我错了,请纠正我(我是新手),每次数据库更改,特别是 wait 集合时,前端都会更改以反映这一点(我最终会找到一个中值)。
但是,我遇到了Meteor.subscribe('wait') 的问题,它应该返回 mongo 集合的选择,但不是。我相信这会导致我目前收到的错误消息Uncaught TypeError: Cannot convert undefined or null to object。当我记录返回的数据(如图所示)时,我得到的是undefined。我知道该查询有效,因为当我在 Meteor.isServer 内部运行它时,它会返回集合中的一个文档。
那么如何使用 getMeteorData(如下所示)从 wait 集合返回数据,并让它在数据库发生更改(添加新文档等)时更新 waitTime DOM 对象?
Venue = React.createClass({
render() {
var self = this;
var venueName = this.props.params.venueName;
return (
<div className='venue'>
<h1>This is the Venue {venueName}</h1>
<WaitTime />
<div className='wait-time-chooser'>
<div className="red" onClick={self.waitTime.bind(this,venueName,'red')}>RED</div>
<div className="yellow" onClick={self.waitTime.bind(this,venueName,'yellow')}>YELLOW</div>
<div className="green" onClick={self.waitTime.bind(this,venueName,'green')}>GREEN</div>
</div>
</div>
);
},
waitTime(currentVenue,time) {
sendWaitTime(currentVenue,time);
}
});
function sendWaitTime(venue,time) {
var userId = Meteor.user()._id;
$.ajax({
type: "POST",
url: "/wait?venue=" + venue + "&wait=" + time + "&user=" + userId,
success: function(response){
console.log(response);
},
error: function(response){
console.log("Error:" + JSON.stringify(response));
}
});
}
WaitTime = React.createClass({
mixins: [ReactMeteorData],
render() {
return (
<div>
<h3>WAIT TIME: {!$.isEmptyObject(this.data)? this.data.wait : <p>Loading...</p>}</h3>
</div>
);
},
componentDidMount() {
// wait for task...
},
getMeteorData() {
var data = {};
var handle = Meteor.subscribe('wait');
if(handle.ready()) {
data.wait = Wait.findOne({});
console.log(data);
}
return data;
}
});
【问题讨论】:
-
您能发布您的发布代码吗?为什么你
posting 到服务器而不是使用 Meteor 方法? -
@MasterAM 你有什么建议可以替代使用
post?我正在使用此处显示的参数从服务器向 API 发送请求。我把发布代码放上来 -
从服务器上的流星方法调用 API。如果这是一个普通的http请求,你甚至可以在方法中使用同步语法,这样可以简化代码。
标签: javascript mongodb meteor reactjs