英文:
Is it bad practice to use the null-forgiving operator with `useRef`?
问题
以下的做法是否被视为不良实践?
const Component: React.FC<{}> = () => {
    const ref = React.useRef<HTMLDivElement>(null!);
    return <div ref={ref} />;
}
具体来说,我指的是使用 null!。
如果没有空值强制操作符,我们需要每次都进行检查,例如
if (ref.current) {
   // ... 使用 ref.current
}
英文:
Would the following be considered bad practice?
const Component: React.FC<{}> = () => {
    const ref = React.useRef<HTMLDivElement>(null!);
    return <div ref={ref} />;
}
Specifically, I'm referring to the use of null!.
Without the null-forgiving operator, we'd need to do a check like
if (ref.current) {
   // ... use ref.current
}
each time.
答案1
得分: 2
好的。
英文:
> Would the following be considered bad practice?
>
>     const Component: React.FC<{}> = () => {
>         const ref = React.useRef<HTMLDivElement>(null!);
>      
>         return <div ref={ref} />;
>     }
Pretty much. It's not doing anything good for you, and it's potentially masking a null access later on – notably, while the component is being unmounted.
Suppose we added an (unwisely coded) effect to the component, with a cleanup callback:
useEffect(() => {
    ref.current.focus();
    return () => ref.current.blur();
});
When the effect cleanup is run, ref.current will be null. Typescript would normally detect this and report 'ref.current' is possibly null, but by initialising the ref with null! we've asserted (falsely) that ref.current is never null. So, instead of detecting the problem during coding, we get a runtime error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论