在我上一篇关于如何传递setState
给上下文 API 的子项的成员的建议之后,我有以下代码:
export interface IShowProviderProps {
shows: IShow[];
setShows: (currentShows: IShow[], shows: IShow[]) => void;
sort: string;
setSort: (sort: string) => void;
query: string;
setQuery: (sort: string) => void;
showType: string;
setShowType: (sort: "movie" | "tv") => void;
page: number;
setPage: (page: number) => void;
}
export const ShowContext = createContext<IShowProviderProps | null>(null);
export const ShowProvider = ({ children }: Props): JSX.Element => {
const [shows, setShows] = useState<IShow[]>([]);
const [sort, setSort] = useState<string>("popularity.desc");
const [query, setQuery] = useState<string>("");
const [showType, setShowType] = useState<"movie" | "tv">("movie");
const [page, setPage] = useState<number>(1);
const providerValue: IShowProviderProps = {
shows,
setShows,
sort,
setSort,
query,
setQuery,
showType,
setShowType,
page,
setPage
};
return <ShowContext.Provider value={providerValue}>{children}</ShowContext.Provider>;
export const useShows = () => useContext(ShowContext);
当我对孩子们使用上下文时,我会尝试这样的事情
const {shows, setShows} = useShows();
我得到错误:
IShowProviderProps 类型上不存在属性“shows” | 空值
我必须这样做:
const providerValues = useShows();
然后
providerValues?.shows
(没有?我可能为空)
我该怎么办?谢谢