使用钩子时 React 批处理状态更新功能吗? [英] Does React batch state update functions when using hooks?

查看:30
本文介绍了使用钩子时 React 批处理状态更新功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于类组件,this.setState 在事件处理程序内部调用批处理.但是如果状态在事件处理程序之外更新并使用 useState 钩子会发生什么?

For class components, this.setState calls batch if inside event handlers. But what happens if state is updated outside the event handler and using useState hook?

function Component() {
  const [a, setA] = useState('a');
  const [b, setB] = useState('b');

  function handleClick() {
    Promise.resolve().then(() => {
      setA('aa');
      setB('bb');
    });
  }

  return <button onClick={handleClick}>{a}-{b}</button>
}

它会立即渲染 aa - bb 吗?或者它会是 aa - b 然后是 aa - bb?

Will it render aa - bb right away? Or it will be aa - b and then aa - bb?

推荐答案

TL;DR – 如果状态更改是异步触发的(例如包装在承诺中),它们将不会被批处理;如果它们是直接触发的,它们将被批处理.

TL;DR – if the state changes are triggered asynchronously (e.g. wrapped in a promise), they will not be batched; if they are triggered directly, they will be batched.

我已经设置了一个沙箱来试试这个:https://codesandbox.io/s/402pn5l989

I've set up a sandbox to try this out: https://codesandbox.io/s/402pn5l989

import React, { Fragment, useState } from 'react';
import ReactDOM from 'react-dom';

import './styles.css';

function Component() {
  const [a, setA] = useState('a');
  const [b, setB] = useState('b');
  console.log('a', a);
  console.log('b', b);

  function handleClickWithPromise() {
    Promise.resolve().then(() => {
      setA('aa');
      setB('bb');
    });
  }

  function handleClickWithoutPromise() {
    setA('aa');
    setB('bb');
  }

  return (
    <Fragment>
    <button onClick={handleClickWithPromise}>
      {a}-{b} with promise
    </button>
    <button onClick={handleClickWithoutPromise}>
      {a}-{b} without promise
    </button>
      </Fragment>
  );
}

function App() {
  return <Component />;
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

我制作了两个按钮,一个触发包装在承诺中的状态更改,例如您的代码示例,另一个直接触发状态更改.

I've made two buttons, one triggers the state changes wrapped in a promise like in your code example, the other triggers the state changes directly.

如果你看控制台,当你点击with promise"按钮时,它会首先显示a aabb,然后是a aab bb.

If you look at the console, when you hit the button "with promise", it will first show a aa and b b, then a aa and b bb.

所以答案是否定的,在这种情况下,它不会立即渲染 aa - bb,每个状态变化都会触发一个新的渲染,没有批处理.

So the answer is no, in this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching.

但是,当您单击无承诺"按钮时,控制台会立即显示 a aab bb.

However, when you click the button "without promise", the console will show a aa and b bb right away.

因此,在这种情况下,React 会批量处理状态更改并同时为两者进行一次渲染.

So in this case, React does batch the state changes and does one render for both together.

这篇关于使用钩子时 React 批处理状态更新功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆