Meteor.call 并将对象传递给渲染的组件



我正在使用Meteor从服务器获取数据并根据某些GET参数进行渲染。我的网址是/course/:subject/:number;使用 React Router,我正确获取参数并使用Meteor.call函数从 Meteor 获取数据(这也很好用。我得到了我正在寻找的数据。Meteor 返回一个对象,我想将其传递给将由 React 渲染的组件中。

但是,调用render方法时nullthis.state.thisClass。如果我使用componentWillMount而不是componentDidMountrender被调用两次:一次课程为 null,这会导致错误,一次没有错误并且使用正确的课程(尽管,由于存在错误,页面只是一个白屏。

我是否误解了componentWillMountcomponentDidMount的运作方式?我应该做点别的事情吗?

import React, { Component, PropTypes } from 'react';
import { Meteor } from "meteor/meteor";
import CourseCard from './CourseCard.jsx';
// Permalink component - Component to render a CourseCard after searching for it in the database
export default class Permalink extends Component {
constructor (props) {
super(props);
const number  = this.props.match.params.number;
const subject = this.props.match.params.subject.toLowerCase();
this.state = {
number: number,
subject: subject,
thisClass: null
};
}
componentDidMount () {
Meteor.call("getCourseByInfo", this.state.number, this.state.subject, (err, foundClass) => {
if (!err && foundClass) {
this.setState({
thisClass: foundClass
});
}
else {
// 404
}
});
}
render () {
return <CourseCard course={ this.state.thisClass } />;
}
}

当this.state.thisClass为空或空时,不渲染CourseCard怎么样?

render () {
return (
<div>
{
this.state.thisClass ? &&
<CourseCard course={ this.state.thisClass } />
}
</div>
);
}

相关内容

最新更新