使用 Zustand/React(shorthand 语法)获取多个状态
Fetching multiple states with Zustand/React (shorthand syntax)
从 Zustand 存储获取状态的两种方式是否在状态更改时重新呈现相同?
文档中描述的方法:
const nuts = useStore(state => state.nuts)
const honey = useStore(state => state.honey)
Shorthand:
const { nuts, honey } = useStore()
简答
不,这些方法并不相同。
长答案
如zustand readme所述:
Fetching everything
You can, but bear in mind that it will cause the component to update
on every state change!
const state = useStore()
因此,当您 select 使用 selector 的某些状态片段时,组件只会 update/rerender 当 selected 值发生变化时。
当您在不向其传递任何参数的情况下调用 useStore()
时,您实际上是在将您的组件订阅到整个状态。作为一个比喻,您可以说“zustand 将要求组件在状态树中的任何位置发生任何状态更改时 update/rerender”。 shorthand 语法中的对象解构只是语法糖,可以更快地将变量分配给对象属性。 useStore()
returns(并订阅组件)的值仍然是整个状态。
因此,如果您使用 const { nuts, honey } = useStore()
,您可能 运行 会遇到性能问题。这些问题是否会引起注意取决于应用程序,但我想说使用 selectors 很容易,而不必担心它。
进一步的建议
如果您需要在单个 useStore(...)
调用中 select 所有状态切片,推荐的方法是为此使用合适的 select 或。
引用自 Selecting multiple state slices
import shallow from 'zustand/shallow'
// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)
// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)
// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useStore(state => Object.keys(state.treats), shallow)
从 Zustand 存储获取状态的两种方式是否在状态更改时重新呈现相同?
文档中描述的方法:
const nuts = useStore(state => state.nuts)
const honey = useStore(state => state.honey)
Shorthand:
const { nuts, honey } = useStore()
简答
不,这些方法并不相同。
长答案
如zustand readme所述:
Fetching everything
You can, but bear in mind that it will cause the component to update on every state change!
const state = useStore()
因此,当您 select 使用 selector 的某些状态片段时,组件只会 update/rerender 当 selected 值发生变化时。
当您在不向其传递任何参数的情况下调用 useStore()
时,您实际上是在将您的组件订阅到整个状态。作为一个比喻,您可以说“zustand 将要求组件在状态树中的任何位置发生任何状态更改时 update/rerender”。 shorthand 语法中的对象解构只是语法糖,可以更快地将变量分配给对象属性。 useStore()
returns(并订阅组件)的值仍然是整个状态。
因此,如果您使用 const { nuts, honey } = useStore()
,您可能 运行 会遇到性能问题。这些问题是否会引起注意取决于应用程序,但我想说使用 selectors 很容易,而不必担心它。
进一步的建议
如果您需要在单个 useStore(...)
调用中 select 所有状态切片,推荐的方法是为此使用合适的 select 或。
引用自 Selecting multiple state slices
import shallow from 'zustand/shallow'
// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)
// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)
// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useStore(state => Object.keys(state.treats), shallow)