Как передать данные от родительского к дочернему компоненту несколько раз в React? - PullRequest
0 голосов
/ 09 января 2019

Я загружаю данные из массива в родительский компонент и передаю его дочерним компонентам несколько раз. Я заметил, что первый элемент из массива отправляется дочернему элементу, но после этого остальные компоненты не передаются / не принимаются дочерним элементом. Вот пример кода, который я использую для доступа к массиву:

{(() => {
switch(data.questions[this.state.index].question_type) {
    case "RadioQuestion":   console.log(JSON.stringify(this.state.radioQuestions[this.state.index]));
                            return <RadioQuestion
                                      radioQuestion = { this.state.radioQuestions[this.state.index] }
                                      handleRadio = { this.handleRadio } />;
    case "TextQuestion":   console.log(JSON.stringify(this.state.textQuestions[this.state.index]));
                           return <TextQuestion
                                      textQuestion = { this.state.textQuestions[this.state.index] }
                                      handleText = { this.handleText } />;
    case "FileUpload": return <FileUpload index = { this.state.index } />;
    default: return <h2>Unknown Question Format</h2>
}
})()}

Я зарегистрировал (console.log ()), что данные из соответствующих массивов над правильными элементами загружаются из массивов с использованием индекса.

Похоже, что в соответствующих дочерних элементах состояние не обновляется после добавления первого элемента:

// Radio Component
constructor(props) {
    super(props);

    this.state = {
        radioQuestion: this.props.radioQuestion
    };

    this.handleRadioText = this.handleRadioText.bind(this);
    this.handleRadioSelect = this.handleRadioSelect.bind(this);
}

// Text Component
constructor(props) {
    super(props);

    this.state = {
        textQuestion: this.props.textQuestion
    };

    this.handleTextChange = this.handleTextChange.bind(this);
}

Что-то я пропускаю или делаю неправильно? Буду признателен за любые отзывы, спасибо.

Ответы [ 2 ]

0 голосов
/ 09 января 2019
If you have requirement to pass data at index = 0 to array.length then you can use the map function to render the child component till the array length

{(() => { array.map((a, index) => {
  switch(data.questions[this.state.index].question_type) {
    case "RadioQuestion":   
      console.log(JSON.stringify(this.state.radioQuestions[index]));
      return <RadioQuestion 
                radioQuestion={ this.state.radioQuestions[index] }
                handleRadio = { this.handleRadio } />;
    case "TextQuestion":   
      console.log(JSON.stringify(this.state.textQuestions[index]));
      return <TextQuestion
                textQuestion = { this.state.textQuestions[index] }
                handleText = { this.handleText } />;
    case "FileUpload": return <FileUpload index={ index } />;
    default: return <h2>Unknown Question Format</h2>
 }
})})()}
0 голосов
/ 09 января 2019

React не знает, что ваш массив был изменен с момента его неизменности. вы можете создать еще один массив, добавить к нему новое значение и передать его в дочерний компонент. Поскольку это не содержит полный код, я покажу пример, как это сделать

 var newArray = this.state.arr.slice();    
 newArray.push("new value");   
 this.setState({arr:newArray})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...