【问题标题】:How do Toggle using Zustand如何使用 Zustand 进行切换
【发布时间】:2021-06-29 17:36:38
【问题描述】:

我使用 Zusand 创建了以下商店:

import create from "zustand"

const useStore = create((set) => ({
  show: false,
  toggleShow: () => set((state) => ({ show: !state.show })),
}))

我认为这是切换show 值的正确方法。然而,打字稿并不高兴——它在!state.show 中的show 下方有一条红色波浪线,并带有以下错误消息:

Property 'show' does not exist on type 'object'.ts(2339)
any

知道为什么我会收到该错误消息以及如何使用 Zusand 正确设置切换功能吗?

谢谢。

【问题讨论】:

  • 你解决了吗?如果有,怎么做?

标签: reactjs typescript zustand


【解决方案1】:

Typescript 不知道你的 state 应该是什么样子,所以它假设 state 是一个普通的对象。

要解决这个问题,您可以为您的商店定义一个类型。然后,您可以将该类型作为泛型传递给 create 函数:

type MyStore = {
    show: boolean;
    toggleShow: () => void;
};

// note the "<MyStore>" next to create
const useStore = create<MyStore>((set) => ({
    show: false,
    toggleShow: () => set((state) => ({ show: !state.show})),
}))

这使 typescript 知道哪些属性会出现在您的商店中。它不会再为 !state.show 部分抛出错误,并且无论您何时使用商店,它都会提供有意义的自动完成功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-08
    • 2023-01-25
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多