2016-10-03 168 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

相關問題