猿问

React setState 不符合直觉

我们说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;


慕妹3146593
浏览 384回答 2
2回答

慕田峪9158850

setState本身是异步的,会积累到一定程度给你更新状态,并不是马上set就会马上change,内部有做优化的
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答