【问题标题】:Meteor.call and passing object to a rendered componentMeteor.call 并将对象传递给渲染的组件
【发布时间】:2018-07-02 17:10:09
【问题描述】:

我正在使用 Meteor 从服务器获取数据并根据某些 GET 参数呈现它。我的网址是/course/:subject/:number;使用 React Router,我可以正确获取参数并使用 Meteor.call 函数从 Meteor 获取数据(这也可以正常工作。我得到了我正在寻找的数据。) Meteor 返回一个我想要的对象传递给将由 React 呈现的组件。

但是,当调用 render 方法时,this.state.thisClassnull。如果我使用componentWillMount 而不是componentDidMount,则render 会被调用两次:一次是课程为空,这会导致错误,一次是没有错误且课程正确(但是,因为有错误,该页面只是一个白屏。)

我是否误解了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 } />;
    }
}

【问题讨论】:

  • 抱歉,您的渲染方法中似乎没有selectedClass 的任何实例,您的意思是thisClass
  • 是的,我就是这个意思。谢谢你接听!
  • 那么追溯一下,你能注销foundClass是什么吗?我认为问题在于回调和 setState 调用之间
  • 好的,看起来componentDidMount 根本没有被调用,因为组件从未安装,因为我期望的项目不在那里。我应该早点发现的。将其更改为componentWillMount 会导致render 发生两次;第一个 thisClass 为空,导致错误,第二个 thisClass 等于我要查找的内容。
  • 您可以随时在其周围添加条件if (this.state.thisClass) &lt;CourseCard... /&gt;?

标签: javascript reactjs meteor react-router


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2019-12-05
    • 2016-08-04
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多