Skip to main content

batch()

batch((fn: () => void))

v7.0.0 中添加

¥added in v7.0.0

信息

如果你使用的是 React 18,则不需要使用 batch API。React 18 会自动批处理所有状态更新,无论它们在哪里排队。

¥If you're using React 18, you do not need to use the batch API. React 18 automatically batches all state updates, no matter where they're queued.

React 的 unstable_batchedUpdates() API 允许事件循环标记中的任何 React 更新一起批处理到单个渲染通道中。React 已经在内部将其用于自己的事件处理程序回调。这个 API 实际上是 ReactDOM 和 React Native 等渲染器包的一部分,而不是 React 核心本身。

¥React's unstable_batchedUpdates() API allows any React updates in an event loop tick to be batched together into a single render pass. React already uses this internally for its own event handler callbacks. This API is actually part of the renderer packages like ReactDOM and React Native, not the React core itself.

由于 React-Redux 需要在 ReactDOM 和 React Native 环境中工作,因此我们在构建时从正确的渲染器导入此 API 供我们自己使用。我们现在也重新公开了这个函数,并将其重命名为 batch()。你可以使用它来确保在 React 之外分派的多个操作仅导致单个渲染更新,如下所示:

¥Since React-Redux needs to work in both ReactDOM and React Native environments, we've taken care of importing this API from the correct renderer at build time for our own use. We also now re-export this function publicly ourselves, renamed to batch(). You can use it to ensure that multiple actions dispatched outside of React only result in a single render update, like this:

import { batch } from 'react-redux'

function myThunk() {
return (dispatch, getState) => {
// should only result in one combined re-render, not two
batch(() => {
dispatch(increment())
dispatch(increment())
})
}
}

参考

¥References