Skip to content

Commit 51c1eb1

Browse files
committed
fix: closure trap
1 parent 4917265 commit 51c1eb1

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

React/sandboxs/src/App.jsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import CountDown from './pages/CountDown.jsx'
2525
import { Modal } from './components/index.js'
2626

2727
import This from './test/This.js'
28+
import Num from './test/Num.js'
2829

2930
const el = (
3031
<>
@@ -41,6 +42,7 @@ const el = (
4142
</Modal>
4243

4344
<This/>
45+
<Num/>
4446
</>
4547
)
4648

React/sandboxs/src/test/Num.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import React, { useState, useEffect, useRef } from "react"
2+
3+
export default function () {
4+
const [num, setNum] = useState(0)
5+
6+
// useEffect(() => {
7+
// setInterval(() => {
8+
// console.log(num)
9+
// }, 1000)
10+
// }, [])
11+
12+
useEffect(() => {
13+
const timer = setInterval(() => {
14+
console.log(num)
15+
}, 1000)
16+
return () => clearInterval(timer)
17+
}, [num])
18+
19+
const curNumRef = useRef(num)
20+
curNumRef.current = num // 更新、同步
21+
useEffect(() => {
22+
const timer = setInterval(() => {
23+
console.log('===cur num ref', curNumRef.current)
24+
}, 1000)
25+
return () => clearInterval(timer)
26+
}, [])
27+
28+
return (
29+
<button onClick={() => setNum(num + 1)}>
30+
{num}
31+
</button>
32+
)
33+
}

0 commit comments

Comments
 (0)