如何在React中多次将数据从父组件传递到子组件?

时间:2019-01-09 04:01:51

标签: reactjs react-native ecmascript-6

我正在从父组件中的数组加载数据,并将其多次传递给子组件。我注意到数组中的第一项被发送给孩子,但是之后其余的组件没有被孩子传递/接收。这是我用来访问数组的代码示例:

{(() => {
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 :(得分:0)

React不知道自数组不可变以来已对其进行了更改。您可以做的是创建另一个数组,然后向其中添加新值,然后将其传递给Child组件。由于其中不包含完整的代码,因此我将向您展示如何执行此操作的示例

 var newArray = this.state.arr.slice();    
 newArray.push("new value");   
 this.setState({arr:newArray})

答案 1 :(得分:0)

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>
 }
})})()}