有時在 return 的時候想使用 console.log 去觀察一些 value 的時候,都會發現會重覆做多了一次。
例如在新的 create-react-app template 之中加一個沒有用的 useState 和在 return 的時候加一句 console.log。
在 npm start 後使用 F12 功能查看,還是會有兩句的 testing 出現。
一直以來都沒有理會這一個現象...
直到看到這篇文章
https://reactjs.org/docs/strict-mode.html#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:
原來如此... 在 Strict mode 之中把我的行動重覆兩次,這樣就能解釋為什麼我的 console.log 永遠都是會顯示兩行了。
在文中之中所說的 Strict mode 這個限制只會在 development 之中發生,我把以上的 script build 一次之後再用 local server 運行,果然只會顯示只有一行。
不過在文中的最後有以下的提示,在 React 版本 17 之後, console.log() 就不會再顯示第二次由 Strict Mode 所作出的 log 了,但為免日後還是抱有一樣的擬問,還是記錄一下。
Note:
Starting with React 17, React automatically modifies the console methods like
console.log()to silence the logs in the second call to lifecycle functions. However, it may cause undesired behavior in certain cases where a workaround can be used.




















