到目前为止,我正在制作一个有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) …Run Code Online (Sandbox Code Playgroud) 我正在使用ReactJS构建一个非常原始的测验应用程序,我无法更新Questions组件的状态.它的行为是它questions向DOM 呈现数组的正确索引,尽管this.state.questionNumber总是落后一步handleContinue():
import React from "react"
export default class Questions extends React.Component {
constructor() {
super()
this.state = {
questionNumber: 1
}
}
//when Continue button is clicked
handleContinue() {
if (this.state.questionNumber > 3) {
this.props.unMount()
} else {
this.setState({
questionNumber: this.state.questionNumber + 1
})
this.props.changeHeader("Question " + this.state.questionNumber)
}
}
render() {
const questions = ["blargh?", "blah blah blah?", "how many dogs?"]
return (
<div class="container-fluid text-center">
<h1>{questions[this.state.questionNumber - 1]}</h1>
<button …Run Code Online (Sandbox Code Playgroud) 在我的扑克应用程序中,我有一系列的手,每一手都是随机选择的卡片对象的数组,有价值和适合:
[ [ { value: 5, suit: 's' },
{ value: 4, suit: 's' },
{ value: 6, suit: 'c' },
{ value: 11, suit: 'd' },
{ value: 12, suit: 'c' } ],
[ { value: 9, suit: 'd' },
{ value: 12, suit: 'h' },
{ value: 8, suit: 'c' },
{ value: 12, suit: 's' },
{ value: 2, suit: 's' } ],
[ { value: 4, suit: 'h' },
{ value: 6, suit: 's' },
{ …Run Code Online (Sandbox Code Playgroud) 我在我的非常基本的 React 应用程序中有一个表单,我想允许用户输入文本并通过更新状态来创建他们的用户名。然而,当点击“确定”按钮时,创建的用户名会在页面上出现大约半秒钟,然后页面会自动刷新并恢复默认状态。只有当按钮包含在表单元素中时才会发生这种情况。它工作正常,当我删除表单元素时页面不会刷新,但是我不想牺牲引导程序表单的样式和格式。这是我的渲染方法:
render() {
return (
<div class="container-fluid text-center">
<form class="form-inline">
<input type="text" class="form-control" placeholder="UserName"/>
<button onClick={this.createUser.bind(this)} class="btn btn-primary">OK</button>
</form>
<h1>User: {this.state.userName}</h1>
<h1>Points: {this.state.points}</h1>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)