为什么调用 useEffect 外部的函数而调用没有依赖数组的 useEffect 内部的函数?

Why does a function outside useEffect get called while a function inside useEffect without dependency array doesn't?

直到今天我还认为没有依赖数组的 useEffect 内的代码和 useEffect 外的代码都会在每次重新渲染时触发,但后来我发现了这个奇怪的情况,我不明白为什么会这样。

THIS 示例中,第一次单击按钮时,它会触发 setState 为不同的值,因此它会重新呈现并调用两个 console.log,但第二次单击按钮时使用相同的值调用 setState,仍然 外部 console.log 被调用,但是 useEffect 内部的 console.log 没有...为什么? 这不是一个完全重新渲染?如何在不再次触发 useEffect 的情况下重新评估组件?

下次单击该按钮时没有任何反应,因为使用相同的值调用 setState 不会触发重新渲染,但第一次会出现我不理解的奇怪的半重新渲染。

提前致谢。

我会回答我的问题:

此行为实际上在 official docs 中进行了解释,无需担心,因为它不是“真实的”渲染。

这是相关部分:

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. [...]

所以基本上 React 会评估函数,所以外部 console.log 将被调用,但随后它会在不重新渲染子项或触发 useEffect

的情况下退出