2016-10-03 155 views
0

所以我试图将状态传递给一个问题组件。由于某种原因,国家并没有被传染。我敢肯定,这件事显而易见,但我可以在这一件事上使用另一套眼睛。谢谢!道具没有传递给子组件

import React from 'react'; 
import Question from './Question'; 
import firebase from 'firebase'; 

var questions = [{ qtext : "", options: [], id:0, answer: ""}, { qtext : "", options: [], id:1, answer: "" }]; 

const QuizBuilderForm = React.createClass({ 
    getInitialState: function() { 
     return { 
      questions 
     }; 
    }, 
    addQuestion: function(questions, id) { 
     questions = this.state.questions; 
     questions.push({ qtext : "", options: [], id: this.state.questions.length }); 
     this.setState({ 
      questions: questions 
     }); 
    }, 
    handleSubmit: function(event) { 
     event.preventDefault(); 
     console.log(this.state.questions); 
     this.firebaseRef = firebase.database().ref('quizzes'); 
     this.firebaseRef.push({ 
     question: this.state.questions 
    }); 
     this.refs.form.reset(); 
     this.setState({ 
      question: [{ qtext : "", options:[], id: 0, answer: ""}, {qtext: "", options:[], id: 1, answer: ""}] 
     }); 
    }, 
    render: function() { 
     {this.state.questions.map((question, index) => { 
      <Question {...this.props} key={index} index={index} question={question} /> 
      console.log(question); 
     } 
    )}; 
     return (
      <form className="quiz-form" onSubmit={this.handleSubmit} ref="form"> 
       <Question /> 
       <button type="button" className="add-question" onClick= {this.addQuestion} disabled={this.state.questions.length === 5}>{this.state.questions.length < 5 ? 'Add another question' : 'Question limit reached!'}</button> 
       <button type="submit">Create Quiz</button> 
      </form>  
     ); 
    } 
}); 

export default QuizBuilderForm; 

回答

0

这样做questions = this.state.questions;你引用的对象,而不是它的克隆,因此不触发对组件的状态的更新。我通常使用lodash这部分,并做questions = _.cloneDeep(this.state.questions);

也你的render看起来不正确。试试这个版本。

render: function() { 
    var questions = this.state.questions.map((question, index) => { 
     <Question {...this.props} key={index} index={index} question={question} /> 
     console.log(question); 
    }); 

    return (
     <form className="quiz-form" onSubmit={this.handleSubmit} ref="form"> 
      {questions} 
      <button type="button" className="add-question" onClick= {this.addQuestion} disabled={this.state.questions.length === 5}>{this.state.questions.length < 5 ? 'Add another question' : 'Question limit reached!'}</button> 
      <button type="submit">Create Quiz</button> 
     </form>  
    ); 
} 
+0

谢谢!对于您的渲染方法,我会收到意外令牌的错误。它抱怨第一个'。'在'{this.state.questons.map ....}'中。 – maxwellgover

+1

'var questions = this.state.questions.map((question,index)=> {Question {... this.props} key = {index} index = {index} question = {question} /> console.log(question); });' 只需要删除包裹整个函数 – finalfreq

+0

@finalfreq哇的块。好。非常感谢。 – maxwellgover