Skip to content

在 React 18 之前的 React 事件处理程序之外调用操作

¥Calling actions outside a React event handler in pre React 18

因为如果在事件处理程序之外调用 React,它会同步处理 setState,所以在事件处理程序之外更新状态将强制 React 同步更新组件。因此,存在遭遇僵尸子效应的风险。为了解决这个问题,需要将操作封装在 unstable_batchedUpdates 中,如下所示:

¥Because React handles setState synchronously if it's called outside an event handler, updating the state outside an event handler will force react to update the components synchronously. Therefore, there is a risk of encountering the zombie-child effect. In order to fix this, the action needs to be wrapped in unstable_batchedUpdates like so:

jsx
import { unstable_batchedUpdates } from 'react-dom' // or 'react-native'

const useFishStore = create((set) => ({
  fishes: 0,
  increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 })),
}))

const nonReactCallback = () => {
  unstable_batchedUpdates(() => {
    useFishStore.getState().increaseFishes()
  })
}

更多细节:https://github.com/pmndrs/zustand/issues/302

¥More details: https://github.com/pmndrs/zustand/issues/302

Zustand v5.0 中文网 - 粤ICP备13048890号