亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Setstate 重新渲染

使用 Setstate 重新渲染

心有法竹 2022-10-08 17:31:53
使用 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
查看完整描述

1 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

你試圖解構一個深層對象,但解構{ ...st }只創建一個淺拷貝,即counter屬性的內容仍將來自先前的狀態,這在 React 中是不允許的。


最簡單的解決方法是復制該屬性counter:


  flipCoin() {

      let num = Math.round(Math.random());

      let face = num === 0 ? 'heads' : 'tails';


      this.setState((st) => {

          const copy = { ...st };

          copy.counter = { ...st.counter };

          copy.flips++;

          copy.counter[face]++;

          copy.currFace = face;

          return copy;

      });

  }

或扁平化您的州的結構。


查看完整回答
反對 回復 2022-10-08
  • 1 回答
  • 0 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號