Skip to content

combine

combine 中间件允许你通过将初始状态与添加新状态切片和操作的状态创建器函数合并来创建一个有凝聚力的状态。这真的很有用,因为它会自动推断类型,因此不需要显式类型定义。

¥combine middleware lets you create a cohesive state by merging an initial state with a state creator function that adds new state slices and actions. This is really helpful as it automatically infers types, so there’s no need for explicit type definitions.

这使得状态管理更加直接和高效,因为中间件使用不需要柯里化版本的 `create` 和 `createStore`。

¥[!TIP] This makes state management more straightforward and efficient by making curried version of create and createStore not necessary for middleware usage.

js
const nextStateCreatorFn = combine(initialState, additionalStateCreatorFn)

类型

¥Types

签名

¥Signature

ts
combine<T, U>(initialState: T, additionalStateCreatorFn: StateCreator<T, [], [], U>): StateCreator<Omit<T, keyof U> & U, [], []>

参考

¥Reference

combine(initialState, additionalStateCreatorFn)

参数

¥Parameters

  • initialState:你希望状态最初为的值。它可以是任何类型的值,除了函数。

    ¥initialState: The value you want the state to be initially. It can be a value of any type, except a function.

  • additionalStateCreatorFn:以 set 函数、get 函数和 store 作为参数的函数。通常,你将返回一个包含要公开的方法的对象。

    ¥additionalStateCreatorFn: A function that takes set function, get function and store as arguments. Usually, you will return an object with the methods you want to expose.

返回

¥Returns

combine 返回状态创建器函数。

¥combine returns a state creator function.

用法

¥Usage

使用推断类型创建存储

¥Creating a store with inferred types

此示例展示了如何创建存储并自动推断类型,因此你无需明确定义它们。

¥This example shows you how you can create a store and get types automatically inferred, so you don’t need to define them explicitly.

ts
import { createStore } from 'zustand/vanilla'
import { combine } from 'zustand/middleware'

const positionStore = createStore(
  combine({ position: { x: 0, y: 0 } }, (set) => ({
    setPosition: (position) => set({ position }),
  })),
)

const $dotContainer = document.getElementById('dot-container') as HTMLDivElement
const $dot = document.getElementById('dot') as HTMLDivElement

$dotContainer.addEventListener('pointermove', (event) => {
  positionStore.getState().setPosition({
    x: event.clientX,
    y: event.clientY,
  })
})

const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {
  $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`
}

render(positionStore.getInitialState(), positionStore.getInitialState())

positionStore.subscribe(render)

这是 html 代码

¥Here's the html code

html
<div
  id="dot-container"
  style="position: relative; width: 100vw; height: 100vh;"
>
  <div
    id="dot"
    style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"
  ></div>
</div>

故障排除

¥Troubleshooting

TBD

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