我目前正在使用 Meteor + React + MongoDB + FlowRouter。我想将选定的课程添加到我的课程中。
我成功地在 Course.jsx 中插入数据并转到 MyCourse,但我不知道为什么它会渲染两次,第一次我的数据正确打印在控制台上,但第二次数据 find() 为空 []。
[ { _id: '3nHTJb9gjNWi2JqZL', user_id: 123, course_id: [ 1, 2 ] } ]
客户端/组件/Course.jsx
Course = React.createClass({
mixins: [ReactMeteorData],
propTypes: {
courseId: React.PropTypes.number.isRequired,
},
getMeteorData () {
return {
currentUser : Meteor.user(),
courseDetail: AllCoursesCol.findOne({
id: this.props.courseId
})
}
},
onPressGetGames(e)
{
e.preventDefault()
if (this.data.currentUser)
{
Meteor.call("addToMyCourses", this.props.courseId, (error) => {
if (error) {
console.log("Update Course Failed")
}
else {
console.log("Update Course Success")
}
})
FlowRouter.go("MyCourses")
}
else
{
FlowRouter.go("Login")
}
},
render() {
return (
<div className="container-fluid">
<div className="row">
<div className="col-sm-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src="https://www.youtube.com/embed/x0nfdbx0Wls" allowFullScreen></iframe>
</div>
</div>
<div className="col-sm-4">
<button btn btn-success onClick={this.onPressGetGames}> Get Games </button>
</div>
</div>
<div className="row">
<h1 className="display-5"> Course Description </h1>
<p> {this.data.courseDetail.long_des} </p>
</div>
</div>
)
}
})
客户端/组件/MyCourses.jsx
MyCourses = React.createClass({
mixins: [ReactMeteorData],
getMeteorData () {
return {
myCoursesId: MyCoursesCol.findOne({user_id: Meteor.userId()})
}
},
render() {
let displayMyCourses
if (this.data.myCoursesId)
{
displayMyCourses = (
<div className="card-columns">
{
this.data.myCoursesId.map((id) => {
console.log(id)
var course = AllCoursesCol.findOne({id: id})
console.log(course)
return (
<MyCourseCard key={course.id} courseId={course.id} title={course.title} shortDes={course.short_des}/>
)
})
}
</div>
)
}
else
{
displayMyCourses = (
<h5 className="text-xs-center"> You have no course. Go to Browse Course and get some courses. </h5>
)
}
return (
<div className="container-fluid">
{displayMyCourses}
</div>
)
}
})
lib/Router.jsx
FlowRouter.route("/browsecourses/:courseId", {
name: "Course",
action (params) {
renderMainLayoutWith(<Course courseId={parseInt(params.courseId)}/>)
}
})
FlowRouter.route("/mycourses", {
name: "MyCourses",
subscriptions: function() {
this.register("myCourses", Meteor.subscribe("myCourses"))
},
action (params) {
renderMainLayoutWith(<MyCourses/>)
}
})
服务器/publish.jsx
Meteor.publish("myCourses", () => {
if (!this.userId) {
throw new Meteor.Error("not-authorized")
}
var data = MyCoursesCol.find({user_id: this.userId})
return data
})