reactjs - 如何在 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);
}
我有什么遗漏或做错了吗?希望有任何反馈,谢谢。
解决方案
React 不知道你的数组因为它是不可变的而被改变了。您可以做的是创建另一个数组并向其添加新值并将其传递给子组件。由于这不包含完整的代码,我将展示一个示例如何做到这一点
var newArray = this.state.arr.slice();
newArray.push("new value");
this.setState({arr:newArray})
推荐阅读
- procrun - 如何通过退出代码使用 Procrun 自动重启 Java 应用程序
- c - 具有不同规格的 sizeof
- .net - 从 Windows 10 运行时,ClickOnce 不会取消注册/重新注册 VSTO 解决方案
- javascript - Azure 函数更新文档中的 CosmosDB SQL 数组
- python - 使用 Python 解析无效 JSON - 无效转义导致错误
- python - 如果用户给出了错误的答案,我如何重复输入字符串?
- javascript - 为什么 [1,2,3] <= [1,2,3] 在 javascript 中为真?
- reactjs - 无法读取未定义的属性“showNotification”
- django - 将 BinaryField 的文件上传小部件添加到 Django Admin
- c++ - 我需要做什么才能让 cocoapods 用 C++ 构建?