我现在有一个心理障碍,我有一个 HOC 组件正在检查如下所示的功能标志:
const withEnabledFeatures = (WrappedComponent: any) => {
class WithEnabledFeatures extends React.Component<any> {
enabledFeatures = (): Array<string> => {
if (window === undefined) return [];
return window.AH.featureFlags;
}
isFeatureEnabled = (feature: string): boolean => {
return this.enabledFeatures.includes(feature);
}
render() {
return (
<WrappedComponent
enabledFeatures={this.enabledFeatures()}
isFeatureEnabled={this.isFeatureEnabled}
{...this.props}
/>
)
}
}
};
export default withEnabledFeatures;
我将在另一个组件中将其用作道具,例如
isFeatureEnabled('feature_a');
true,如果不存在,则返回 false。
我的问题是我的isFeatureEnabled
函数是否正确?
不,您不是在调用this.enabledFeatures
作为方法,而是在尝试访问其上的成员。使用 this.enabledFeatures().
此外,HOC 工厂方法不返回扩展类。
const withEnabledFeatures = (WrappedComponent: any) => {
return class WithEnabledFeatures extends React.Component<any> {
enabledFeatures = (): Array<string> =>
(window === void 0) ? [] : window.AH.featureFlags;
isFeatureEnabled = (feature: string): boolean =>
this.enabledFeatures().includes(feature); // <-- Here, ()
render() {
return (
<WrappedComponent
enabledFeatures={this.enabledFeatures()}
isFeatureEnabled={this.isFeatureEnabled}
{...this.props}
/>
)
}
}
};
export default withEnabledFeatures;
(我还选择性地压缩了您的代码并添加了最佳实践,void 0
(
在 HOC
中添加了 return 以WithEnabledFeatures
并更正了 isFeatureEnabled
return 语句
const withEnabledFeatures = (WrappedComponent: any) => {
return class WithEnabledFeatures extends React.Component<any> {
enabledFeatures = (): Array<string> => {
if (window === undefined) return [];
return window.AH.featureFlags;
}
isFeatureEnabled = (feature: string): boolean => {
return this.enabledFeatures().includes(feature);
}
render() {
return (
<WrappedComponent
enabledFeatures={this.enabledFeatures()}
isFeatureEnabled={this.isFeatureEnabled}
{...this.props}
/>
)
}
}
};
export default withEnabledFeatures;