import React, { Component } from "react";
import "./Game.css";
class Game extends Component {
static defaultProps = {
list: ["rock", "paper", "scissors"]
};
constructor(props) {
super(props);
this.state = {
play: false,
random: null,
user: null,
winner: false
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.setState({
play: !this.state.play
});
}
handleClick(event) {
//paper beats Rock
//scissors beats Paper
// rock beats scissors
// 1 > 0
// 2 > 1
//0 > 2
if (this.state.winner) {
return;
}
let hasWon;
let inputIndex = this.props.list.indexOf(event.target.value);
let ranIndex = this.props.list.indexOf(this.state.random);
if (
(inputIndex === 1 && ranIndex === 0) ||
(ranIndex === 1 && inputIndex === 0)
) {
hasWon = true;
// return this.props.list[1];
} else if (
(inputIndex === 2 && ranIndex === 1) ||
(ranIndex === 2 && inputIndex === 1)
) {
hasWon = true;
} else if (
(inputIndex === 0 && ranIndex === 2) ||
(ranIndex === 0 && inputIndex === 2)
) {
hasWon = true;
}
console.log(this.props.list.indexOf(this.state.random));
this.setState({
user: event.target.value,
random: this.props.list[
Math.floor(Math.random() * this.props.list.length)
],
winner: hasWon
});
}
render() {
let game;
if (this.state.play) {
game = (
<div className="Game-userButtons">
<button
onClick={this.handleClick}
name={this.state.user}
value="rock"
>
Rock
</button>
<button
onClick={this.handleClick}
name={this.state.user}
value="paper"
>
Paper
</button>
<button
onClick={this.handleClick}
name={this.state.user}
value="scissors"
>
Scissor
</button>
<button>Play Again! </button>
</div>
);
} else {
game = (
<div>
<form onSubmit={this.handleSubmit}>
<button>Play </button>
</form>
</div>
);
}
return (
<div>
<h1>Rock, paper, scissors </h1>
<div className="players">
<div className="user">
<i className={`fas fa-hand-${this.state.user}`}></i>
</div>
<div className="robot">
<i className={`fas fa-hand-${this.state.random}`}></i>
</div>
</div>
{game}
</div>
);
}
}
export default Game;
我试图通过比较用户的索引和随机生成的索引来确定石头剪刀布游戏的获胜者。在handleClick() 中,我编写了赢得游戏的潜在条件以及转化为潜在奖金的索引。当我 console.log this.state.random 的索引时,呈现的状态似乎比正在控制台的状态落后一步。因此,条件有效,但视觉效果没有任何意义。我怎样才能解决这个问题?感谢您的宝贵时间!
最佳答案
我想我发现了您的问题,它与this.state.random有关。如果您检查这部分中的代码:
let ranIndex = this.props.list.indexOf(this.state.random);
您正在将randIndex与状态中的先前随机值进行比较,我认为您应该创建一个新的随机值,而不是采用状态的值:
let randIndex = this.props.list[
Math.floor(Math.random() * this.props.list.length)
];
在设置状态下完成比较后更新它:
this.setState({
user: event.target.value,
random: randIndex,
winner: hasWon
});
关于javascript - 为什么我的父组件中的状态落后了一步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107023/