小编典典

ReactJS Array.push函数在setState中不起作用

reactjs

到目前为止,我正在制作一个具有3个问题的原始测验应用程序,无论是对还是错。在我的handleContinue方法中,有一个调用将用户输入从无线电表单推入userAnswers数组。对于的第一次运行,它工作正常handleContinue,之后抛出一个错误:Uncaught TypeError: this.state.userAnswers.push is not a function(…)

import React from "react"

export default class Questions extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      questionNumber: 1,
      userAnswers: [],
      value: ''
    }

    this.handleContinue = this.handleContinue.bind(this)
    this.handleChange = this.handleChange.bind(this)
  }

  //when Continue button is clicked
  handleContinue() {
    this.setState({
      //this push function throws error on 2nd go round
      userAnswers: this.state.userAnswers.push(this.state.value),
      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)
  }

  handleChange(event) {
    this.setState({
      value: event.target.value
    })
  }

  render() {
    const questions = [
      "Blargh?",
      "blah blah blah?",
      "how many dogs?"
    ]
    return (
      <div class="container-fluid text-center">
        <h1>{questions[this.state.questionNumber - 1]}</h1>
        <div class="radio">
          <label class="radio-inline">
            <input type="radio" class="form-control" name="trueFalse" value="true" 
            onChange={this.handleChange}/>True
          </label><br/><br/>
          <label class="radio-inline">
            <input type="radio" class="form-control" name="trueFalse" value="false" 
            onChange={this.handleChange}/>False
          </label>
          <hr/>
          <button type="button" class="btn btn-primary" 
          onClick={this.handleContinue}>Continue</button>
        </div>
      </div>
    )
  }
}

阅读 315

收藏
2020-07-22

共1个答案

小编典典

不要直接修改状态!通常,请尝试避免突变

Array.prototype.push() 变异
就地阵列。因此,从本质上讲,当您push访问内部数组时setState,可以使用来改变原始状态push。由于push返回的是新的数组长度而不是实际的数组长度,因此您将设置this.state.userAnswers为数值,这就是为什么要Uncaught TypeError: this.state.userAnswers.push is not a function(…)进行第二次运行的原因,因为您不能push输入数字。

您需要改用Array.prototype.concat()。它不会改变原始数组,并返回带有新串联元素的新数组。这就是您要在内部执行的操作setState。您的代码应如下所示:

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