ReactJS Array.push function not working in setState

前端 未结 5 1338
粉色の甜心
粉色の甜心 2021-01-17 22:18

I\'m making a primitive quiz app with 3 questions so far, all true or false. In my handleContinue method there is a call to push the users input from a radio fo

5条回答
  •  独厮守ぢ
    2021-01-17 22:47

    You should treat the state object as immutable, however you need to re-create the array so its pointing to a new object, set the new item, then reset the state.

     handleContinue() {
        var newState = this.state.userAnswers.slice();
        newState.push(this.state.value);
    
        this.setState({
          //this push function throws error on 2nd go round
          userAnswers: newState,
          questionNumber: this.state.questionNumber + 1
        //callback function for synchronicity
        }, () => {
          if (this.state.questionNumber > 3) {
            this.props.changeHeader(this.state.userAnswers.toString())
            this.props.unMount()
          } else {
            this.props.changeHeader("Question " + this.state.questionNumber)
          }
        })
        console.log(this.state.userAnswers)
      }
    

    Another alternative to the above solution is to use .concat(), since its returns a new array itself. Its equivalent to creating a new variable but is a much shorter code.

    this.setState({
      userAnswers: this.state.userAnswers.concat(this.state.value),
      questionNumber: this.state.questionNumber + 1
    }
    

提交回复
热议问题