Skip to content

映射和设置用法

¥Map and Set Usage

你需要将 Maps 和 Sets 封装在对象内。当你希望反映其更新时(例如在 React 中),你可以通过在其上调用 setState 来执行此操作:

¥You need to wrap Maps and Sets inside an object. When you want its update to be reflected (e.g. in React), you do it by calling setState on it:

你可以在此处查看 codesandbox:https://codesandbox.io/s/late-https-bxz9qy

¥You can view a codesandbox here: https://codesandbox.io/s/late-https-bxz9qy

js
import { create } from 'zustand'

const useFooBar = create(() => ({ foo: new Map(), bar: new Set() }))

function doSomething() {
  // doing something...

  // If you want to update some React component that uses `useFooBar`, you have to call setState
  // to let React know that an update happened.
  // Following React's best practices, you should create a new Map/Set when updating them:
  useFooBar.setState((prev) => ({
    foo: new Map(prev.foo).set('newKey', 'newValue'),
    bar: new Set(prev.bar).add('newKey'),
  }))
}

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