interface ContextType {
something: SomethingType[];
}
const Context = createContext<ContextType | undefined>(undefined);
export function ContextProvider({children}){
//some states
const [fetchX] = useLazyQuery(GQL_QUERY);
useEffect(() => { fetchX() }, []);
const contextValue = useMemo(() => {
somethingObjectToMatchContextType
});
return (
<Context.Provider value={contextValue}>
{children}
</Context.Provider>
);
}
export function useX() {
const context = useContext(Context);
if (context === undefined) {
throw new Error('useX must be used within a ContextProvider');
}
return context;
}
2 -Bootstrap.tsx
root.render(
<React.StrictMode>
<ContextProvider>
<App />
</ContextProvider>
</React.StrictMode>
)
3-应用程序上下文中使用的自定义组件
function XForm() {
const { something } = useX();
///rest of code
}
const contextValue = useMemo(() => {
somethingObjectToMatchContextType
});
在此功能中没有返回语句,因此它隐含地返回。然后将分配给要这样做:
undefined
contextValue