React 版本17.0.2
javascript
import React, { useState } from 'react';
const Demo = () => {
const [count, setCount] = useState(0);
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);
console.log('===Demo==');
const add = async () => {
await 10;
setCount(count + 1);
setCount1(count1 + 1);
setCount2(count2 + 1);
};
return (
<div>
<div onClick={add}>button</div>
<div>{count}</div>
<div>{count1}</div>
<div>{count2}</div>
</div>
);
};
export default Demo;
每次点击button ,log会执行3次,当我们把async方法里面的await去掉,让他变成正常方法,那么点击button就会执行一次。
同样代码在React 版本18.2.0时候点击button,log只会打印一次。
再次修改代码对同一个状态同时执行多次更改
javascript
import React, { useState } from 'react';
const Demo = () => {
const [count, setCount] = useState(0);
console.log('===Demo==');
const add = async () => {
await 10;
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
};
return (
<div>
<div onClick={add}>button</div>
<div>{count}</div>
</div>
);
};
export default Demo;
React 17.0.2 log会打次2次,也就是对于同一状态同时多次修改,那么React会合并一起更改,log打印两次是因为在开发环境下,会多执行一次。
React18,还是只会打印一次log。
总结:
React 17.0.2 在异步方法中,多个状态同时修改会造成页面刷新多次,同一状态同时多次修改页面只会刷新一次
React 18 默认在异步方法中开启了批量更新没有问题。
React 17.0.2解决方案:使用unstable_batchedUpdates
javascript
import React, { useState } from 'react';
import { unstable_batchedUpdates } from 'react-dom'; // 批量更新状态时使用
const Demo = () => {
const [count, setCount] = useState(0);
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);
console.log('===Demo==');
const add = async () => {
await 10;
unstable_batchedUpdates(() => {
setCount(count + 1);
setCount1(count1 + 1);
setCount2(count2 + 1);
});
};
return (
<div>
<div onClick={add}>button</div>
<div>{count}</div>
<div>{count1}</div>
<div>{count2}</div>
</div>
);
};
export default Demo;
log只会打印一次