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

问题描述:

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

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); 
+0

Retun应该是有效的DOM元素。在这里,您正在返回不是有效的DOM元素的“问题”。 – Ved

+0

谢谢你的回复。根据官方教程,容器可以像数组一样返回变量。这不是为了呈现任何内容,而仅仅是将数据传递给预期的组件。 https://www.meteor.com/tutorials/react/collections 奇怪的是无法访问组件中的数据。 –

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); 
+1

非常感谢。我可能会为QuestionList放置一个错误的路径,或者QuestionList本身有错误。反正它现在有效。再次感谢。 –