为什么在什么都没有改变的情况下使用 Effect 重新渲染?

Why useEffect re-rendering when nothing has changed?

我有 2 个这样的 React 功能组件:

const Test = function (props) {
    console.log("rendered");
    useEffect(() => {}, []);

    return <div>Testing</div>;
}

const Parent = function () {
    return <div>Component: <Test /></div>;
}

正如我们在上面看到的,没有状态或道具更改仍然浏览器控制台显示 "rendered" 两次,但如果我评论 useEffect 它只会打印一次。我尝试 google 它但没有找到任何适当的原因。

这是由于 React.StrictMode
来自 React Docs - Detecting unexpected side effects

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

在为 production 构建项目时,不应发生这种情况。

因为React.StrictMode. If there's no useEffect (or any statefulness), react might not render it twice in StrictMode because it doesn't need to. StrictMode renders components twice to make sure that everything works properly and there are no deprecated lifecycle methods or other practices that are problematic. It's whole purpose is to make sure that your application will work well with the more stringent requirements for concurrent mode。它仅在开发模式下运行这些检查,以免影响生产构建中的性能。

在此CodeSandbox中,您可以看到严格模式对相同的组件渲染了两次,而普通模式则不会。