04-react-state和setState

2020-10-16  本文已影响0人  低头看云

react-state和setState

state

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 1 };
    }
    // ...
}

setState

setState(updater[, callback])
this.setState((state, props) => stateChange);
this.setState({ count: 1 });

setState 的基本使用

this.setState({ count: this.state.count + 1 });
class Test extends React.Component {
    state = {
        count: 1
    };
    componentDidMount() {
        this.setState({
            count: this.state.count + 1
        });
        this.setState({
            count: this.state.count + 1
        });
        // 批量合并更新 count为2
    }
    render() {
        return <div>{this.state.count}</div>;
    }
}
class Test extends React.Component{
    state = {
        count : 1
    }
    componentDidMount(){
        this.setState((state, props) => {
            console.log("state,props :", state, props);
            return { count: state.count + 1 };
        });
        this.setState((state, props) => ({
            count: state.count + 1
        })
        this.setState((state, props) => ({
            count: state.count + 1
        })
        // count 值为4

    }
    render(){
        return (
            <div>{this.state.count}</div>
        )
    }
}
this.setState(
    {
        count: 2
    },
    () => {
        console.log("this.setState的回调函数");
    }
);

setState 小结

1.setState 只在合成事件和钩子函数中是异步的,在原生事件setTimeout 中是同步的
2.setState 的异步并不是说内部异步代码是实现的,其本身的代码是同步的.

总结:属于原生 js 执行的空间,setState 就是同步,被 react 处理过的就是异步

3.setState 的批量更新中,

上一篇下一篇

猜你喜欢

热点阅读