useEffect(fn, []) 包裹的代码和useEffect(fn, []) 外面的代码有什么区别?

What are the differences between the code wrapped in useEffect(fn, []) and the code outside useEffect(fn, [])?

新的 React Hooks 功能很酷,但有时会让我感到困惑。特别是,我将这段代码包裹在 useEffect 钩子中:

const compA = ({ num }) => {
  const [isPositive, check] = useState(false);
  useEffect(() => {
    if (num > 0) check(true); 
  }, []);

  return (//...JSX);
};

上面useEffect里面的代码只会执行一次。那么,如果我将代码从 useEffect 中提取出来,会有什么区别,如下所示:

const compA = ({ num }) => {
  const [isPositive, check] = useState(false);

  if (num > 0) check(true);

  return (//...JSX);
};

在第二种情况下,代码将在每个 re-render.

执行

这是组件的更好版本:

const compA = ({ num }) => {
  const [isPositive, check] = useState(false);
  useEffect(() => {
    if (num > 0) check(true); 
  }, [num]);

  return (//...JSX);
};

在这种情况下,效果(很大程度上取决于 num)仅在 num 属性发生变化时使用。

供参考: https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect

无论如何,在我看来,在这个非常简单的案例中使用副作用是多余的! 通过在每次渲染时检查是否 num > 0,代码将 运行 更快,而不是先检查 num 是否更改,然后检查它是否 > 0.. 所以你应该避免 useEffect 并坚持你的第二段代码