为了账号安全,请及时绑定邮箱和手机立即绑定

使用 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 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号