arrays - 反应JS | 对象内部的连接数组
问题描述
我目前正在开发一个 React JS 应用程序,我有一个Array里面有Objects,并且在Objects里面有Arrays。
先上代码,
constructor() {
super();
this.state = {
namaSantri: null,
examTitle: 'PLP BAHAS Arab Talaqqi',
examLevel: 0,
examType: 'Ujian 1 Tulis',
vocabQ: [{questionTitle: 'Question Title', question: ['Question 1', 'Question 2']}],
};
}
componentDidMount(){
var questionEx = {questionTitle: 'Question Title2', question: ['Question 1']}
var anotherArray = ['Question 2']
var addIndex = questionEx.question.concat(anotherArray)
this.setState({
vocabQ: [...this.state.vocabQ, addIndex]
})
}
所以我有一个数组,这里是 vocabQ,它包含对象,其中包含我的 QuestionTitles 和我的 Questions 数组。
我想在这里为 Quesiton 对象(包含 questionTitle 和 questions)创建一个输入程序,所以我尝试在 addIndex 处连接我的数组,但它什么也没显示。帮助?
我的渲染,
render() {
/**SOMETHING THAT YOU NEED TO WRITE TO OUTPUT AN ARRAY? */
const map = this.state.vocabQ.map((d) => <p key={d.questionTitle}>{d.questionTitle} {d.question}</p>);
return (
<div /**DIV PAGE START */
className="App">
<div /**DIV HEADER START */
className="DivHeader">
<Center>
<p className="ExamTitle">{this.state.examTitle}</p>
</Center>
<Center>
<p className="ExamLevel">Level {this.state.examLevel}</p>
</Center>
<Center>
<p className="ExamType">{this.state.examType}</p>
</Center>
<Center>
<div className="NameInput">
<InputText value={this.state.namaSantri} onChange={(e) => this.setState({value: e.target.namaSantri})} />
{/**HERE IS WHERE THE ARRAY SHOULD BE */}
<span> {map}</span>
</div>
</Center>
{/**DIV HEADER END */}
</div>
<div /**DIV VOCAB QUESTIONS START */>
{/**DIV VOCAB QUESTIONS END */}
</div>
{/**DIV PAGE END*/}
</div >
);
}
注意:它只显示“问题标题问题 1 问题 2” 图像
解决方案
试试这样:
componentDidMount(){
var questionEx = {questionTitle: 'Question Title2', question: ['Question 1']}
var anotherArray = ['Question 2']
var addIndex = questionEx.question.concat(anotherArray)
this.setState({
vocabQ: [...this.state.vocabQ, ...addIndex] //<----This "..." is the part that has changed
})
}
您基本上必须在两个数组上使用扩展运算符才能使其以您想要的方式工作。前往https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Spread_operator https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Spread_operator学习更多关于那个。
推荐阅读
- mule - 组合数组的元素并重新格式化输出
- reactjs - React 样式最佳实践。全局或组件级别
- sql - 每月需要将单行转换为多行
- symfony - 交响乐。如何构建表格?
- laravel - 如何从 Laravel 中的 Storage/App 目录访问文件
- swift - 如何从谷歌自动完成中获取所选地点的正确纬度
- python - 用于从 systemd 日志返回 systemd 单元日志消息列表的 Python 脚本
- c++ - 如何在 Windows Cmake 中将 Dlib 设置为静态安装的共享库
- docker - Vagrant 和 Docker 之间的 Redis 连接被拒绝
- javascript - Chrome 扩展程序“接收端不存在。” 错误