react setState 伪代码实现

640?wx_fmt=png

我们大家都知道 react 的 setState 是异步的(也可以理解成同步的),在react 组件声明周期内的多次 setState 会进行合并处理。

看下面代码


	
    componentDidMount(){ 	
        this.setState({	
            count:0	
        })	
        this.setState({	
            count: 1	
        })	
        this.setState({	
            count: 2	
        })	
        this.setState({	
            count: 3	
        });	
        console.log(this.state);	
    }

setState 内部将数据进行合并,主要使用了共享结构,下面是模拟的伪代码实现。

function React(){	
    this.state={}; 	
    this.nextState=null;//保存合并后的state	
    this.renderEndCallback=[];//保存回调方法	

	
}	

	
React.prototype.setState=function(obj,callback){	
    //obj是对象	
    if(obj && typeof obj === 'object'){//如果是对象则进行合并	
            this.nextState = {...this.state,...this.nextState,...obj};	
            if(typeof callback==='function'){	
                this.renderEndCallback.push(callback);	
            }	
    }	

	
    //obj 是函数	
    if(obj  && typeof obj==='function'){	
        this.nextState = this.nextState ? this.nextState:({...this.state});	
        var tempState = obj(this.nextState);//此处省略 props 参数	

	
        //进行state 的合并	
        this.nextState = {...this.state,...this.nextState,...tempState};	
    }	

	
}	

	
//获得最新 state	
React.prototype.getState=function(){	
    this.state={...this.nextState};	
    return this.state;	
}	

	
// 用来获得最新的state	
React.prototype.render=function(){	
   var state=this.getState();	
   this.renderEndCallback.forEach((fn)=>(fn.call(this)));	
}	

调用


	
var title = new React();	

	
title.state={	
    count:0,	
    name:'前端张大胖'	
}	

	
title.setState({	
    count:1	
});	

	
console.log(1,title.state);	

	
title.setState({	
    count:2	
},function(){	
    console.log(2,'callback',this.state);	
});	

	
console.log(3,title.state);	

	
title.setState((preState)=>{	
    return {	
        count:preState.count+3,	
        age:25,	
        address:'北京'	
    }	
});	

	

	
console.log(4,title.state);	

	

	
title.setState({	
    count:1	
});	

	

	
title.setState((preState)=>{	
    console.log(5,preState);	
    return {	
        count:preState.count+3	
    }	
});	

	
title.render();	

执行结果

640?wx_fmt=png

以上模拟代码并非是 react 内部实现逻辑,只是模拟实现了相同的的输出结果,如有问题还请指正。

 

觉得有用的话 请动动手

分享到朋友圈或者技术交流群

让更多人受益

长按关注 >>>
盘它
640?wx_fmt=jpeg
640?wx_fmt=png

我就知道你在看!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zz_jesse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值