主题
subscribeWithSelector
subscribeWithSelector
中间件允许你根据当前状态订阅特定数据。
¥subscribeWithSelector
middleware lets you subscribe to specific data based on current state.
js
const nextStateCreatorFn = subscribeWithSelector(stateCreatorFn)
类型
¥Types
签名
¥Signature
ts
subscribeWithSelector<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/subscribeWithSelector', never]], []>
变量
¥Mutator
ts
['zustand/subscribeWithSelector', never]
参考
¥Reference
subscribeWithSelector(stateCreatorFn)
参数
¥Parameters
stateCreatorFn
:以set
函数、get
函数和store
作为参数的函数。通常,你将返回一个包含要公开的方法的对象。¥
stateCreatorFn
: A function that takesset
function,get
function andstore
as arguments. Usually, you will return an object with the methods you want to expose.
返回
¥Returns
subscribeWithSelector
返回状态创建器函数。
¥subscribeWithSelector
returns a state creator function.
用法
¥Usage
订阅部分状态更新
¥Subscribing partial state updates
通过订阅部分状态更新,你可以注册一个回调,该回调在存储的部分状态更新时触发。我们可以使用 subscribe
进行外部状态管理。
¥By subscribing to partial state updates, you register a callback that fires whenever the store's partial state updates. We can use subscribe
for external state management.
ts
import { createStore } from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
type PositionStoreState = { position: { x: number; y: number } }
type PositionStoreActions = {
setPosition: (nextPosition: PositionStoreState['position']) => void
}
type PositionStore = PositionStoreState & PositionStoreActions
const positionStore = createStore<PositionStore>()(
subscribeWithSelector((set) => ({
position: { x: 0, y: 0 },
setPosition: (position) => set({ position }),
})),
)
const $dot = document.getElementById('dot') as HTMLDivElement
$dot.addEventListener('mouseenter', (event) => {
const parent = event.currentTarget.parentElement
const parentWidth = parent.clientWidth
const parentHeight = parent.clientHeight
positionStore.getState().setPosition({
x: Math.ceil(Math.random() * parentWidth),
y: Math.ceil(Math.random() * parentHeight),
})
})
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((state) => state.position, render)
const logger: Parameters<typeof positionStore.subscribe>[0] = (x) => {
console.log('new x position', { x })
}
positionStore.subscribe((state) => state.position.x, logger)
这是 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