【发布时间】:2018-07-02 17:10:09
【问题描述】:
我正在使用 Meteor 从服务器获取数据并根据某些 GET 参数呈现它。我的网址是/course/:subject/:number;使用 React Router,我可以正确获取参数并使用 Meteor.call 函数从 Meteor 获取数据(这也可以正常工作。我得到了我正在寻找的数据。) Meteor 返回一个我想要的对象传递给将由 React 呈现的组件。
但是,当调用 render 方法时,this.state.thisClass 是 null。如果我使用componentWillMount 而不是componentDidMount,则render 会被调用两次:一次是课程为空,这会导致错误,一次是没有错误且课程正确(但是,因为有错误,该页面只是一个白屏。)
我是否误解了componentWillMount 和componentDidMount 的功能?我应该做点别的吗?
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) <CourseCard... />?
标签: javascript reactjs meteor react-router