主题
不可变状态和合并
¥Immutable state and merging
与 React 的 useState
一样,我们需要不可变地更新状态。
¥Like with React's useState
, we need to update state immutably.
这是一个典型的例子:
¥Here's a typical example:
jsx
import { create } from 'zustand'
const useCountStore = create((set) => ({
count: 0,
inc: () => set((state) => ({ count: state.count + 1 })),
}))
set
函数用于更新存储中的状态。因为状态是不可变的,所以应该是这样的:
¥The set
function is to update state in the store. Because the state is immutable, it should have been like this:
js
set((state) => ({ ...state, count: state.count + 1 }))
但是,由于这是一种常见模式,set
实际上合并了状态,我们可以跳过 ...state
部分:
¥However, as this is a common pattern, set
actually merges state, and we can skip the ...state
part:
js
set((state) => ({ count: state.count + 1 }))
嵌套对象
¥Nested objects
set
函数仅在一个级别合并状态。如果你有一个嵌套对象,则需要明确合并它们。你将使用扩展运算符模式,如下所示:
¥The set
function merges state at only one level. If you have a nested object, you need to merge them explicitly. You will use the spread operator pattern like so:
jsx
import { create } from 'zustand'
const useCountStore = create((set) => ({
nested: { count: 0 },
inc: () =>
set((state) => ({
nested: { ...state.nested, count: state.nested.count + 1 },
})),
}))
对于复杂的用例,请考虑使用一些有助于不可变更新的库。你可以参考 更新嵌套状态对象值。
¥For complex use cases, consider using some libraries that help with immutable updates. You can refer to Updating nested state object values.
替换标志
¥Replace flag
要禁用合并行为,你可以为 set
指定一个 replace
布尔值,如下所示:
¥To disable the merging behavior, you can specify a replace
boolean value for set
like so:
js
set((state) => newState, true)