ReactJS Array.push function not working in setState

前端 未结 5 1353
粉色の甜心
粉色の甜心 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条回答
  •  萌比男神i
    2021-01-17 22:41

    Do not modify state directly! In general, try to avoid mutation.

    Array.prototype.push() mutates the array in-place. So essentially, when you push to an array inside setState, you mutate the original state by using push. And since push returns the new array length instead of the actual array, you're setting this.state.userAnswers to a numerical value, and this is why you're getting Uncaught TypeError: this.state.userAnswers.push is not a function(…) on the second run, because you can't push to a number.

    You need to use Array.prototype.concat() instead. It doesn't mutate the original array, and returns a new array with the new concatenated elements. This is what you want to do inside setState. Your code should look something like this:

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

提交回复
热议问题