简体   繁体   English

反应批处理如何工作?

[英]How does react batch works?

I have one select field and onselect event I have three setStates call to update my local states.我有一个选择字段和 onselect 事件我有三个 setStates 调用来更新我的本地状态。

Observation: The number of setStates written causes that much re render.观察:写入的 setState 的数量会导致大量的重新渲染。 When I commented setState it reduced accordingly.当我评论 setState 时,它​​相应地减少了。

Ex:前任:

<select name="cars" id="cars" onselect={(e) => handleSelect(e)}>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

const handleSelect = e => {
    setInvalid(false);
    setValue("some value");
    setError("some error");
};


My understanding was it will do batching and cause only one render.我的理解是它会进行批处理并且只导致一次渲染。 But got 3 re-renders.但是得到了 3 次重新渲染。 Any explanation to this?对此有何解释?

with react18 Automatic Batching gets applied by default ,if you have return n number of state updates inside a function react will only re-render the component once .默认情况下,使用react18自动批处理,如果您在函数内返回 n 次状态更新,react 只会重新渲染组件一次。 If you want to stop this behavior you can use flushSync如果你想停止这种行为,你可以使用flushSync

import { flushSync } from "react-dom";
 const clickMe = () => {
    setName("abc");
    flushSync(() => {
      setCount(30);
      // react will create a re-render here
    });
    setAge(30);
    setPin(1111);
  };

so for the above example react will re-render your component twice when clicking on clickMe() function, but if you are on the older version < 18 the re-render will take place n number of times.因此对于上面的示例,当单击 clickMe() 函数时,react 将重新渲染您的组件两次,但如果您使用的是older version < 18 ,则重新渲染将发生 n 次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM