我正在开发一个游戏:石头,纸和剪刀。我在更新状态时遇到问题。我使用了componentWillReceiveProps方法。游戏可以正常运行,但是当我重新启动游戏时,会收到一条有关游戏结束的消息。不利于重置状态。
import React, { Component } from 'react';
import './ResultInfo.scss';
class ResultInfo extends Component {
constructor(props) {
super(props);
this.state = {
userPoint: 0,
pcPoint: 0,
roundLimit: this.props.round,
roundWinner: '',
}
}
componentWillReceiveProps() {
if (this.state.roundLimit > this.state.userPoint && this.state.roundLimit > this.state.pcPoint) {
if ((this.props.id === "paper" && this.props.ran === "stone") ||
(this.props.id === "stone" && this.props.ran === "scissors") ||
(this.props.id === "scissors" && this.props.ran === "paper")) {
this.setState(({ userPoint, roundWinner }) => ({
userPoint: userPoint + 1,
roundWinner: 'User'
}));
}
else if (this.props.id === this.props.ran) {
this.setState(({ roundWinner }) => ({
roundWinner: 'Draw',
}))
}
else {
this.setState(({ pcPoint, roundWinner }) => ({
pcPoint: pcPoint + 1,
roundWinner: 'PC',
}));
}
}
else {
alert('End Game');
this.setState(({ roundLimit }) => ({
roundLimit: 0,
}));
}
}
render(props) {
return (
<>
<div className="top">You selected: {`${this.props.id}`}</div>
<div>Number of rounds: {`${this.props.round}`}</div>
<div>PC: {`${this.props.ran}`}</div>
<div>Winner: {this.state.roundWinner}</div>
<div>User point: {this.state.userPoint}</div>
<div>PC point: {this.state.pcPoint}</div>
</>
)
}
}
export default ResultInfo;