typescript实现react中的批次式更新

react

欢迎吐槽讨论

  前言

    笔者在React经常使用setState,在学习过程中作笔记以作总结,欢迎讨论。

  关于setState的核心观点    

    1 . 执行setState不都是异步的。

    2 . setState能够缓存多次结果,对最晚的setState进行更新 ( batchedUpdate 批次式更新 )

  代码部分

// typescript

let stateList = [];

let LOCK = false;

const ele = document.getElementById('test');

const view = document.getElementById('v');

const setState = (arg)=>{

if(!LOCK){

render(arg)

}else{

stateList.push(arg);

}

}

const render = (arg)=>{

alert('我只执行了一次render');

view.innerHTML = arg

}

// 启动

ele.onclick = function() {

const myT = new Transaction();

myT.perform(()=>{

console.log('i am cb');

setState('ONE');

setState('TWO');

setState('THREE');

setState('FOUR');

});

}

class Transaction {

constructor() {

}

_init() {

// 上锁

LOCK = true;

console.log('i am init');

}

_close() {

LOCK = false;

console.log('i am close');

// batch update

setState(stateList.pop());

// 解锁、清空stateList

stateList = [];

}

async perform(cb){

await this._init();

cb();

await this._close();

}

}

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

</head>

<body>

<h2>每次执行setState不应该都进行render,而是应该render最后一次setState,观察console更佳</h2>

<h3 >点我</h3>

<h3 ></h3>

<pre>

ele.onclick = function() {

const myT = new Transaction();

myT.perform(()=>{

console.log('i am cb');

setState('ONE');

setState('TWO');

setState('THREE');

setState('FOUR');

});

}

</pre>

<script src="batchUpdate.js"></script>

</body>

</html>

 

 

以上是 typescript实现react中的批次式更新 的全部内容, 来源链接: utcz.com/z/382070.html

回到顶部