I have a plain old color class that I've been using in many places in my app:
const Color = {
[...]
cardBackground: '#f8f8f8',
sidebarBackground: '#eeeeee',
viewportBackground: '#D8D8D8',
[...]
}
export default Color;
It simply works. Now I want to implement dark mode support without changing external modifications to the code. I decided to hook up to state, read it directly and return the appropriate value in getter:
const Color = {
[...]
cardBackground: '#f8f8f8',
get sidebarBackground(){ return lightDark('#eeeeee','#222222') },
viewportBackground: '#D8D8D8',
[...]
}
export default Color;
Where lightDark
is defined as:
export function lightDark<T1, T2>(light:T1, dark:T2){
return themeSelector(store.getState()) == 'dark' ? dark : light;
}
Now I suddenly get an undefined
error in the first place where Color
is accessed (not necessarily Color.sidebarBackground
, but anything inside Color
)
If I modify the code to remove access to the state (just for testing), it starts working:
export function lightDark<T1, T2>(light:T1, dark:T2){
return themeSelector({session:{theme:'dark'}} as any) == 'dark' ? dark : light;
}
What on Earth is going on?
For clarificaition, this is the exact error:
TypeError: Cannot read property 'title' of undefined
where I try to access Color.title
, which appears to be the first reference to Color
in my app (thus, title
is irrelevant).
I also realized that the moment I reference store
in any way at all in the file where Color
is defined, Color
becomes undefined. Even console.log(store);
causes Color
to become undefined.
Found the problem: something import
ed in store
was indirectly accessing Color
at some point, creating a hard-to-detect circular dependency. I got rid of the reference by refactoring a little bit and the problem is solved.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.