使用Meteor React将数据从容器传递到组件

时间:2017-05-25 04:06:57

标签: javascript reactjs meteor

在使用Meteor和React时,我完全坚持将数据从容器传递到组件。我以为我刚刚复制了Meteor React教程中的代码并进行了一些定制,但它并没有以某种方式工作。我想做的是从数据库(QuestionModel)获取数据,并在视图中输出。根据浏览器中的错误消息,renderQuestions()中的this.props.questions未定义...但我明确地将数据传递给组件。 任何人都可以帮我吗?谢谢。

import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Questions as QuestionsModel } from '../../api/questions.js';
import { QuestionList } from '../QuestionList.jsx';

class Questions extends Component{
  renderQuestions(){
    let filteredQuestions = this.props.questions;
    //This doesn't work at all...
    console.log(this.props.questions);
    return filteredQuestions.map((question) => (
      <QuestionList key={question._id} question={question} />
    ));
  }
  render(){
    return (
        <div className="questionlist">
            <ul>{this.renderQuestions()}</ul>
        </div>
    );
  }
}

Questions.propTypes = {
  questions: PropTypes.array.isRequired,
};


export default QuestionsContainer = createContainer(() => {
  //This console.log outputs the data correctly.
  console.log(QuestionsModel.find({}).fetch());
  const questions = QuestionsModel.find({}).fetch();
  return {
    questions,
  };
}, Questions);

1 个答案:

答案 0 :(得分:0)

您的QuestionList组件的代码是什么?

我刚用<li key={question._id}>{question.question}</li>替换它,它对我来说很有效。

其他:你导入/imports/api/questions.js';服务器端吗?

这是我的代码:

import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Questions as QuestionsModel } from '../api/questions.js';
// import { QuestionList } from '../QuestionList.jsx';

class Questions extends Component{
  renderQuestions(){
    let filteredQuestions = this.props.questions;
    //This doesn't work at all...
    console.log(this.props.questions);
    return filteredQuestions.map((question) => (
      <li key={question._id}>{question.question}</li>
    ));
  }
  render(){
    return (
        <div className="questionlist">
            <ul>{this.renderQuestions()}</ul>
        </div>
    );
  }
}

Questions.propTypes = {
  questions: PropTypes.array.isRequired,
};


export default QuestionsContainer = createContainer(() => {
  //This console.log outputs the data correctly.
  console.log(QuestionsModel.find().fetch());
  const questions = QuestionsModel.find({}).fetch();
  return {
    questions,
  };
}, Questions);