使用 Setstate 重新渲染,記錄兩次,正面和反面計數器在每次點擊時增加 +2 而不是 +1 class CoinFlip extends Component { constructor(props) { super(props); this.state = { currFace: 'heads', flips: 0, counter: { heads: 0, tails: 0, }, }; this.flipCoin = this.flipCoin.bind(this); } flipCoin() { let num = Math.round(Math.random()); let face = num === 0 ? 'heads' : 'tails'; this.setState((st) => { const copy = { ...st }; copy.flips++; copy.counter[face]++; copy.currFace = face; return copy; }); } render() { return ( <div> <h1>Lets flip a coin</h1> <Coin face={this.state.currFace} /> <p> Out of {this.state.flips}, there have been {this.state.counter.heads}{' '} heads and {this.state.counter.tails} tail </p> <button onClick={this.flipCoin}>Flip!</button> </div> ); } }記錄時有 2 個帶有雙面值的復制 obj 結果2x 控制臺:計數器:{heads:2,tails:0} currFace:“heads”翻轉:1
使用 Setstate 重新渲染
心有法竹
2022-10-08 17:31:53