I am trying to use static classes in React. However, I keep getting the following error when running the Webpack server locally: Uncaught TypeError: _util_stageHelper__WEBPACK_IMPORTED_MODULE_3__.getStageName is not a function
. I have traced this down to a cyclic dependency in my code.
Here's the structure of my code:
// util/stageHelper.js
import {StageConfiguration} from '../config/StageConfiguration'
export class StageEligibility {
static stageEnabled = StageConfiguration.getEnabled();
static isEligible(key) {
if(stageEnabled) {
return;
}
return key.indexOf('com') > -1;
}
static notifyEligibility() {
if (!this.stageEnabled) {
return;
}
alert('Only the com stages are eligible for viewing');
}
// other other static properties and functions
}
export const getStageName = (key) => {
if (StageEligibility.isEligible(key)) {
return STAGES[key];
}
};
// config/StageConfiguration.js
import {getStageName} from '../util/stageHelper'
export class StageConfiguration {
static config = {
stageName: getStageName('com-openserve') // the code breaks here with the above error
enabled: true,
}
static getEnabled() {
return this.config.enabled;
}
// static properties and functions that make use of this.config
}
I import StageEligibility
in a root React component in my application and call StageEligibility.notifyEligibility()
.
Could someone please provide some ideas on how I can resolve this circular dependency?
Fundamentally, when you have a cycle between modules A and B it means that without careful planning of the loading order (which can be tricky), you can't use resources imported from A in B's top-level code, or resources imported from B in A's top-level code. But your static
property initializers are trying to do just that.
The problem in this specific case looks more fundamental than modules. You have StageConfiguration
trying to use getStageName
as the class is created, and getStageName
tries to use the StageEligibility
class, which tries to use StageConfiguration
. You can't have the creation of class StageConfiguration
rely on StageEligibility
already existing and being fully initialized and have the creation of StageEligibility
rely on StageConfiguration
already existing and being fully initialized. That's a chicken-and-egg logical problem.
Extract the parts that both classes need into a third class/function/data member that each class can use indepdendently, so that that class/function/data member can be created and initialized, and then used as part of creating each of the classes.
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.