英文:
How to define type to allow null in createContext React TypeScript?
问题
I have issue about typescript when creating modal context with typescript, I want to null as default value in createContext but it will causing typescript error
import React from 'react';
type TModal = boolean;
type TModalContext = [TModal, React.Dispatch<React.SetStateAction<TModal>>];
const ModalContext = React.createContext<TModalContext | null>(null); // allow null as default value
const ModalProvider = ({ children }: { children: React.ReactNode }) => {
const modalState = useState<TModal>(false);
return <ModalContext.Provider value={modalState}>{children}</ModalContext.Provider>;
};
const useModalContext = () => React.useContext(ModalContext);
When I call useModalContext hook to use in another component I get an error:
Type 'TModalContext | null' is not an array type.ts(2461)
How can I resolve this issue ?
英文:
I have issue about typescript when creating modal context with typescript, I want to null as default value in createContext but it will causing typescript error
import React from 'react';
type TModal = boolean;
type TModalContext = [TModal, React.Dispatch<React.SetStateAction<TModal>>];
const ModalContext = React.createContext<TModalContext | null>(null); // allow null as defaut value
const ModalProvider = ({ children }: { children: React.ReactNode }) => {
const modalState = useState<TModal>(false);
return <ModalContext.Provider value={modalState}>{children}</ModalContext.Provider>;
};
const useModalContext = () => React.useContext(ModalContext);
When I call useModalContext hook to use in another component I get an error:
> Type 'TModalContext | null' is not an array type.ts(2461)
const [isOpen, setOpen] = useModalContext();
How can I resolve this issue ?
答案1
得分: 1
Solution 1:
因为您告诉编译器 null
是一个有效的值,最简单的方法是在上下文为 null
时抛出一个 Error
:
const useModalContext = () => {
const context = React.useContext(ModalContext);
if(context === null) throw new Error; // 或者在此处执行其他操作
return context
}
如果您始终在上下文内调用钩子,您就不必担心应用程序因 Error
而崩溃。
Solution 2:
另一方面,如果您无法确保钩子始终安全,您应该考虑处理来自调用者的 null
值:
const context = useModalContext();
const [isOpen, setOpen] = context ?? []
英文:
Solution 1:
Because you tell the compile that null
is a valid value, the most simple way is throw an Error
when the context is null
:
const useModalContext = () => {
const context = React.useContext(ModalContext);
if(context === null) throw new Error; // or do other things here
return context
}
You won't to worry about the app crashed by the Error
if you always call the hook inside the context
Solution 2:
On the other hand, if you can't ensure the hook is always safe, you should consider handle the null
value from the caller:
const context = useModalContext();
const [isOpen, setOpen] = context ?? []
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论