1
yena 2023-12-08 02:45:28 +08:00 via iPhone 1
useeffect 默认执行两次
|
2
whj768702 2023-12-08 07:43:12 +08:00 1
是严格模式,看看入口文件中是不是有<StrictMode>标签包裹,在开发环境,严格模式下会执行两次。可以参考下文档。https://react.dev/reference/react/StrictMode
|
3
daleqq 2023-12-08 07:54:38 +08:00 via iPhone 1
Development 模式下默认执行两次 mount 提醒你有没有合理的 cleanup.
"To help you spot them quickly, in development React remounts every component once immediately after its initial mount." |
4
potatowish 2023-12-08 08:46:34 +08:00 via iPhone 1
初学 React 时也遇到过,开发环境下默认是 StrictMode
|
5
realJamespond 2023-12-08 10:38:11 +08:00 1
```
export const useMount = (fn: React.EffectCallback) => { const isMounted = useRef(false) useEffect(() => { if (!isMounted.current) { fn() isMounted.current = true } }, []) } ``` 这样就能只执行一次了 |
6
nodejsexpress 2023-12-08 13:46:00 +08:00
好的,看来还是我太菜了。谢谢楼上的各位大佬!
|