[英]How to define Typescript properties and types for a React Action Hook Store
I am creating a react state management store using hooks, after the 'Action Hooks pattern' described here by Tanner Linsley. 在Tanner Linsley 在这里描述的“动作钩子模式”之后,我正在使用钩子创建一个反应状态管理存储。
I am learning Typescript and am trying to create this project using it but keep running into an error when calling the custom hook to consume the store:我正在学习 Typescript 并尝试使用它创建这个项目,但在调用自定义钩子以使用商店时一直遇到错误:
'Property 'useStore' does not exist on type '() => { Provider: ({ initialValue, children }: { initialValue?: {}; children: any; }) => Element;
'属性'useStore' 不存在于类型 '() => { Provider: ({ initialValue, children }: { initialValue?: {}; children: any; }) => Element; useStore: () => any;}' ts(2339)
useStore: () => any;}' ts(2339)
I tested it in plain react and it is working, so it is a type or property definition issue with Typescript.我在普通的反应中测试了它并且它正在工作,所以它是 Typescript 的类型或属性定义问题。
Generic Store created (No typescript errors):创建通用存储(没有打字稿错误):
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 (the error is shown for both instances of 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,
}))
}
Any advice greatly appreciated.非常感谢任何建议。
The key point of the problem (it's visible in your code sandbox and I've edited your question to include it) is the store
definition.问题的关键点(它在您的代码沙箱中可见,我已经编辑了您的问题以包含它)是
store
定义。
You define store as import store from "./makeStore";
您将商店定义为
import store from "./makeStore";
So store
is a function that, when called, returns an object containing所以
store
是一个函数,当被调用时,它返回一个包含
{
Provider: any;
useStore(): any;
}
when you consume it with store.useStore()
you're making the mistake.当您使用
store.useStore()
使用它时,您就犯了错误。 store
is a function which return value is an object containing the useStore
function. store
是一个函数,它的返回值是一个包含useStore
函数的对象。
Everything goes well replacing一切顺利更换
store.useStore()
with和
store().useStore()
Let me know if you need more help 😊如果您需要更多帮助,请告诉我😊
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.