ReactJS |对象内部的Concat数组

时间:2018-12-12 12:27:55

标签: arrays reactjs object concat

im目前正在使用React JS应用,并且我有一个 Array 其中具有 Objects ,并且在 Objects 内部具有< strong>数组。

首先是代码,

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 Array。

我想在这里为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” image

1 个答案:

答案 0 :(得分:0)

像这样尝试:

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

基本上,您必须在两个数组上都使用spread运算符,才能使其按您想要的方式工作。前往https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Spread_operatorhttps://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Spread_operator进一步了解。