- 解决方法:自定义
useNonNullContextValue
解决
import React, {useContext} from 'react';
export const useNonNullContextValue = <T, >(context: React.Context<T>) => {
const contextValue = useContext(context);
if (!contextValue) {
throw new Error('useNonNullContextValue must be used within a non-null context');
}
return contextValue;
};
type ContextValue = {
appState: User,
setAppState: Dispatch<User>
};
const Context = createContext<ContextValue | null>(null);
const User = () => {
const { appState } = useNonNullContextValue(Context);
return <div>
User:{appState.user.name}
</div>;
};