Zustand入门及使用教程(二--更新状态)
扁平更新
使用新状态调用的 set 函数,它将与存储中的现有状态进行浅层合并。
import { create } from 'zustand'type State = {firstName: stringlastName: string
}type Action = {updateFirstName: (firstName: State['firstName']) => voidupdateLastName: (lastName: State['lastName']) => void
}// Create your store, which includes both state and (optionally) actions
const usePersonStore = create<State & Action>((set) => ({firstName: '',lastName: '',updateFirstName: (firstName) => set(() => ({ firstName: firstName })),updateLastName: (lastName) => set(() => ({ lastName: lastName })),
}))// In consuming app
function App() {// "select" the needed state and actions, in this case, the firstName value// and the action updateFirstNameconst firstName = usePersonStore((state) => state.firstName)const updateFirstName = usePersonStore((state) => state.updateFirstName)return (<main><label>First name<input// Update the "firstName" stateonChange={(e) => updateFirstName(e.currentTarget.value)}value={firstName}/></label><p>Hello, <strong>{firstName}!</strong></p></main>)
}
不可变状态和合并
与 React 的 useState一样,需要不可变地更新状态。
import { create } from 'zustand'const useCountStore = create((set) => ({count: 0,inc: () => set((state) => ({ count: state.count + 1 })),
}))
set 函数用于更新存储中的状态。因为状态是不可变的,所以应该是:
set((state) => ({ ...state, count: state.count + 1 }))
但是,由于这是一种常见的模式,set 实际上合并了状态,我们可以跳过 ...state 部分:
set((state) => ({ count: state.count + 1 }))
嵌套对象
set 函数仅在一个级别合并状态。如果你有一个嵌套对象,则需要明确合并他们。将使用扩展运算符模式:
import { create } from 'zustand'const useCountStore = create((set) => ({nested: { count: 0 },inc: () =>set((state) => ({nested: { ...state.nested, count: state.nested.count + 1 },})),
}))
对于复杂用例,考虑使用一些有助于不可变更新的库。参考 更新嵌套状态对象值。
替换标志
要禁止合并行为,可以为 set 指定一个 replace 布尔值:
set((state) => newState, true)