首页 > 解决方案 > 反应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}&nbsp;{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&nbsp;{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>&nbsp;&nbsp;&nbsp;&nbsp;{map}</span>
            </div>
          </Center>

        {/**DIV HEADER END */}
        </div>

        <div /**DIV VOCAB QUESTIONS START */> 

        {/**DIV VOCAB QUESTIONS END */}
        </div>

      {/**DIV PAGE END*/}
      </div >
    );
  }

注意:它只显示“问题标题问题 1 问题 2” 图像

标签: arraysreactjsobjectconcat

解决方案


试试这样:

  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学习更多关于那个。


推荐阅读