首页 > 解决方案 > 如何在 React 中多次将数据从父组件传递到子组件?

问题描述

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

{(() => {
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);
}

我有什么遗漏或做错了吗?希望有任何反馈,谢谢。

标签: reactjsreact-nativeecmascript-6

解决方案


React 不知道你的数组因为它是不可变的而被改变了。您可以做的是创建另一个数组并向其添加新值并将其传递给子组件。由于这不包含完整的代码,我将展示一个示例如何做到这一点

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

推荐阅读