eslint-plugin-react-hooks应在函数组件中标记createRef的使用

5rgfhyps  于 2022-10-28  发布在  React
关注(0)|答案(2)|浏览(123)

在函数组件中使用createRef几乎肯定是个错误。您可能需要使用useRef来代替。这很容易导致令人困惑的bug。例如,请参阅这个流行的“堆栈溢出”问题。
完全班宁createRef会在类组件上产生误报。我建议添加一个规则,专门在eslint-plugin-react(jsx-eslint/eslint-plugin-react#2966)的函数组件中标记这一点,但他们建议我在这里提交一个问题。
React版本:16.13.1时的React

重现步骤

1.设置eslint-plugin-react-hooks并创建一个使用React.createRef的函数组件。
1.没有任何抱怨。
链接到代码示例:https://codesandbox.io/s/cool-volhard-9zj0s

export default function App() {
  const ref = React.createRef(0);
  // Change to this to make the example work as intended:
  // const ref = React.useRef(0);
  const [, update] = React.useState(0);

  const handleClick = () => {
    ref.current += 1;
    update((n) => n + 1);
  };
  React.useEffect(() => {
    ref.current = 0;
  }, [ref]);

  return (
    <div className="App" ref={ref}>
      <h1>Hello CodeSandbox</h1>
      <h2>Value is {ref.current}</h2>
      <button onClick={handleClick}>Click Me</button>
</div>
  );
}

当前行为

eslint-plugin-react-hooks不会报告问题。

预期行为

eslint-plugin-react-hooks应该报告一个问题,即createRef应该是useRef

hk8txs48

hk8txs481#

IMO这看起来确实像是应该警告的事情,但是eslint-plugin-react-hooks警告它也似乎很奇怪(因为那些规则都是关于钩子的,而createRef不是钩子)。

piwo6bdm

piwo6bdm2#

useRef是一个钩子,这是一个关于将用例迁移到钩子的规则,这似乎是合适的。

相关问题