在使用`useRef`时使用null-forgiving操作符是否是一种不好的做法?

huangapple go评论62阅读模式
英文:

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&lt;{}&gt; = () =&gt; {
    const ref = React.useRef&lt;HTMLDivElement&gt;(null!);

    return &lt;div ref={ref} /&gt;;
}

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(() =&gt; {
    ref.current.focus();
    return () =&gt; ref.current.blur();
});

When the effect cleanup is run, ref.current will be null. Typescript would normally detect this and report &#39;ref.current&#39; 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.

huangapple
  • 本文由 发表于 2023年2月7日 03:45:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定