Meteor.call and passing object to a rendered component

时间:2018-01-23 19:17:35

标签: javascript reactjs meteor react-router

I am working with Meteor to grab data from the server and render it based on certain GET parameters. My URL is /course/:subject/:number; with React Router, I'm getting the parameters correctly and using a Meteor.call function to grab data from Meteor (which also works just fine. I get the data that I'm looking for.) Meteor returns an object that I would like to pass into a component that will be rendered by React.

However, this.state.thisClass is null when the render method is called. If I use componentWillMount instead of componentDidMount, render is called twice: Once with the course as null, which causes an error, and once without an error and with the proper course (though, since there was an error, the page is just a white screen.)

Am I misunderstanding how componentWillMount and componentDidMount function? Should I be doing something else?

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 } />;
    }
}

1 个答案:

答案 0 :(得分:2)

当this.state.thisClass为null或为空时,如何不渲染CourseCard?

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