javascript-ReactJS Array.push函数在setState中不起作用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-ReactJS Array.push函数在setState中不起作用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2321字,纯文字阅读大概需要4分钟。
内容图文
到目前为止,我正在制作一个包含3个问题的原始测验应用程序,无论是对还是错.在我的handleContinue方法中,有一个调用将用户输入从单选表单推入userAnswers数组.在第一次运行handleContinue时,它工作正常,之后抛出一个错误:未捕获的TypeError:this.state.userAnswers.push不是一个函数(…)
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>
)
}
}
解决方法:
Do not modify state directly!通常,请尝试至avoid mutation.
Array.prototype.push()原位更改数组.因此,从本质上讲,当您推送到setState内的数组时,可以使用push更改原始状态.并且由于push返回了新的数组长度而不是实际的数组长度,因此您将this.state.userAnswers设置为数值,这就是为什么会出现Uncaught TypeError的原因:this.state.userAnswers.push不是函数(…),因为您无法输入数字.
您需要改用Array.prototype.concat().它不会改变原始数组,并返回带有新串联元素的新数组.这是您要在setState中执行的操作.您的代码应如下所示:
this.setState({
userAnswers: this.state.userAnswers.concat(this.state.value),
questionNumber: this.state.questionNumber + 1
}
内容总结
以上是互联网集市为您收集整理的javascript-ReactJS Array.push函数在setState中不起作用全部内容,希望文章能够帮你解决javascript-ReactJS Array.push函数在setState中不起作用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。