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

React setState 不符合直觉

React setState 不符合直觉

慕妹3146593 2019-03-20 17:19:14
我们说setState是批量更新但是下面代码显示的star是3有谁知道为什么吗?import React, { Component } from 'react';class App extends Component {    constructor(props) {        super(props);        this.timer = null;        this.state = { star: 0 };    }        componentDidMount() {        this.timer = setTimeout(() => {            this.setState({ num: this.state.star + 1 });            this.setState({ num: this.state.star + 1 });            this.setState({ num: this.state.star + 1 });        }, 5000);    }        render() {        return <div>{this.state.star}</div>;    }        componentWillUnmount() {        clearTimeout(this.timer);    }}export default App;
查看完整描述

2 回答

?
慕田峪9158850

TA贡献1794条经验 获得超8个赞

setState本身是异步的,会积累到一定程度给你更新状态,并不是马上set就会马上change,内部有做优化的


查看完整回答
反对 回复 2019-04-04
  • 2 回答
  • 0 关注
  • 383 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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