【发布时间】:2018-05-28 11:50:55
【问题描述】:
每当我在四个选项中单击正确或错误的“答案”div 时,我都会尝试更新我的组件状态,以更新记分员和计数器。但是,当我控制台注销记分员和计数器值时,无论我回答了多少问题,我总是得到 0。为什么会发生这种情况,如何更新这两个组件状态?
这是我的代码:
export default class QuestionCard extends React.Component {
constructor(props) {
super(props);
this.state = {
scorekeeper: 0,
counter: 0,
hideDiv: false
}
this.handleClick = this.handleClick.bind(this);
this.handleClickCont = this.handleClickCont.bind(this);
}
handleClick(choice) {
if(this.state.counter === 4) {
return console.log('we have four')
}
this.handleClickCont(choice)
}
handleClickCont(choice) {
if(choice === this.props.answer) {
this.setState({scorekeeper: this.state.scorekeeper + 1});
this.setState({counter: this.state.counter + 1});
console.log('scorekeeper ' + this.state.scorekeeper)
console.log('counter ' + this.state.counter)
return this.setState({hideDiv: !this.state.hideDiv});
}
this.setState({scorekeeper: this.state.scorekeeper - 1});
this.setState({counter: this.state.counter + 1});
console.log('scorekeeper ' + this.state.scorekeeper);
console.log(this.state.counter)
this.setState({hideDiv: !this.state.hideDiv});
}
render() {
return (
<div style={{margin: '20px', display: this.state.hideDiv ? 'none' : 'block'}}>
<div>
{this.props.question}
</div>
<div style={{
margin: '20px',
width: '500px',
display: 'flex',
justifyContent: 'space-around',
display: this.state.hideDiv ? 'none' : 'block'
}}>
<div onClick={() => this.handleClick(this.props.choice1)}>
{this.props.choice1}
</div>
<div onClick={() => this.handleClick(this.props.choice2)}>
{this.props.choice2}
</div>
<div onClick={() => this.handleClick(this.props.choice3)}>
{this.props.choice3}
</div>
<div onClick={() => this.handleClick(this.props.choice4)}>
{this.props.choice4}
</div>
</div>
</div>
);
}
}
【问题讨论】:
-
你试过
this.setState(prevState => {counter: prevState.counter + 1});。这样您就不会丢失先前状态的当前值。
标签: reactjs function if-statement components state