我现在有一个思维障碍,我有一个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
函数正确吗?
答案 0 :(得分:1)
否,您不是在调用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
)
答案 1 :(得分:0)
在HOC
中为WithEnabledFeatures
添加了return并更正了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;