【问题标题】:How to define Typescript properties and types for a React Action Hook Store如何为 React Action Hook Store 定义 Typescript 属性和类型
【发布时间】:2019-08-27 19:08:42
【问题描述】:

在 Tanner Linsley 描述的 here 的“动作挂钩模式”之后,我正在使用挂钩创建一个反应状态管理存储。

我正在学习 Typescript,并正在尝试使用它创建这个项目,但在调用自定义钩子以使用商店时一直遇到错误:

'属性'useStore'不存在于类型'() => { Provider: ({ initialValue, children }: { initialValue?: {}; children: any; }) => Element; useStore: () => any;}' ts(2339)

我在普通反应中对其进行了测试并且它正在工作,所以这是 Typescript 的类型或属性定义问题。

已创建通用商店(无打字稿错误):

interface IState {}

const initialState: IState = {}

export default function newStore() {
  const context = React.createContext<IState>(initialState)

  const Provider = ({ initialValue = {}, children }): JSX.Element => {
    const [state, setState] = useState(initialValue)
    const contextValue = useMemo(() => [state, setState], [state])

    return <context.Provider value={contextValue}>{children}</context.Provider>
  }
  const useStore = () => useContext(context)

  return { Provider, useStore }
}

Store Action Hooks(两个 useStore 实例都会显示错误):

import store from "./makeStore";

export const useGalleryOpen = () => {
  const [{ galleryOpen }] = store.useStore()
  return galleryOpen
}

export const useGalleryToggle = () => {
  const [_, setState] = store.useStore()
  return () =>
    setState(prev => ({
      ...prev,
      galleryOpen: !prev.galleryOpen,
    }))
}

非常感谢任何建议。

【问题讨论】:

    标签: reactjs typescript react-hooks react-context react-state-management


    【解决方案1】:

    问题的关键点(它在您的代码沙箱中可见,我已编辑您的问题以包含它)是 store 定义。

    您将 store 定义为 import store from "./makeStore";

    所以store 是一个函数,当被调用时,它会返回一个包含

    的对象
    {
      Provider: any;
      useStore(): any;
    }
    

    当您使用store.useStore() 使用它时,您就犯了错误。 store 是一个函数,它的返回值是一个包含useStore 函数的对象。

    一切顺利,替换

    store.useStore()
    

    store().useStore()
    

    如果您需要更多帮助,请告诉我?

    【讨论】:

    • 我已经尝试过明确定义 Provider 和 useStore 并使用我现在放置的任何接口进行测试,例如。 interface IStore { Provider: any useStore(): any } newStore(): IStore {... 然后 useStore 返回错误 Property 'useStore' does not exist on type '() =&gt; IStore' 我没有正确定义 useStore 函数吗?
    • 您在代码中使用了store.useStore(),但store 是在哪里声明的?我想看看它的类型?
    • 我从 ./makeStore 导入商店。代码片段是独立的组件。因此在上述情况下function store(): IStore 我想我在 IStore..hmm 中声明了 useStore? CodeSandbox Link
    • 我已经用解决方案 ? 更新了答案
    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 2020-12-09
    • 1970-01-01
    • 2021-09-22
    • 2022-08-05
    • 2020-05-21
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多