其他分享
首页 > 其他分享> > 面试题:React中setState

面试题:React中setState

作者:互联网

1、setState是异步操作

2、在同一个地方使用setState, 会合并去取最后一次

3、 验证代码

import React from 'react'

export default class Like012 extends React.Component{
    constructor(props){
        super(props);

        this.state = {
            count: 0
        }
    }

    componentDidMount() {
        /*
          setState是异步的,
          1) 在同一个地方使用setState, 会合并去取最后一次
        */
       /*
       this.setState({
            count: this.state.count + 1
        });
        this.setState({
            count: this.state.count + 2
        });
        this.setState({
            count: this.state.count + 3
        });
        this.setState({
            count: this.state.count + 4
        });
        */

        this.setState({
            count: this.state.count + 1
        }, ()=>{
            console.log(this.state.count);
        });
        this.setState((prevState, prevProps)=>({
            count: prevState.count + 2
        }));
        this.setState((prevState, prevProps)=>({
            count: prevState.count + 3
        }));

        console.log(this.state.count);
    }

    render() {
        const {count} = this.state;
        return (
            <div>
                {count}
            </div>
        )
    }
}

标签:count,面试题,prevState,console,React,state,setState
来源: https://blog.csdn.net/KaiSarH/article/details/111566109