如何解决Eslint 规则 no-invalid-this 和类中的胖箭头函数
我有以下课程:
export class MyClass {
private foos: Foo[];
constructor(foos: Foo[]) {
this.foos = foos;
}
getByA = (myA: Mya): Foo => {
return this.foos.find(foo => foo.a === myA) ?? unknownFoo();
};
}
不幸的是,在我的粗箭头函数中,我收到一条关于无效 this
的警告:
ESLint: Unexpected 'this'.(no-invalid-this)
我的 eslint 插件版本是 4.15.1
除了禁用它之外,我还能做些什么来使此规则正常工作?
解决方法
您收到此错误是因为当您创建箭头函数时,您正在创建一个可以在类的不同上下文中调用的对象。因此,当执行 interface AddedProps {
isOpen: boolean;
toggleOpen: () => void;
}
function withCreateHOC<ChildProps>(
ChildComponent: ComponentType<Omit<ChildProps,keyof AddedProps> & AddedProps>,options: Partial<WithCreateButtonHOCOptions>
) {
return function (props: Omit<ChildProps,keyof AddedProps>) {
const { createComponent,title = 'Create' } = options;
const isOpen = useSelector((state: { isOpen: boolean }) => state.isOpen);
const dispatch = useDispatch();
const toggleOpen = () => {
dispatch({ type: 'TOGGLE_OPEN' });
}
return (
<div>
<ChildComponent
{...props}
toggleOpen={toggleOpen}
isOpen={isOpen}
/>
<div>
<Component.Button
key={'add'}
big={true}
round={true}
primary={true}
onClick={toggleOpen}
className={'float-right'}
tooltip={title}
>
<Component.Icon material={'add'} />
</Component.Button>
</div>
<OpenDrawerWithClose
open={isOpen}
title={title}
setisOpen={toggleOpen}
createComponent={createComponent}
/>
</div>
);
}
}
时,它可能处于 getByA
不存在或不同的上下文中。
一种选择是this
箭头函数的上下文:
bind
有关此错误的更多资源以及如何在正确上下文中正确使用 getByA = (myA: Mya): Foo => {
return this.find(foo => foo.a === myA) ?? unknownFoo();
}.bind(this.foos);
的示例,请查看 here。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。