节流
const Mouse: React.FC = () => {
const [position, setPosition] = useState({ x: 0, y: 0 })
useEffect(() => {
//节流操作,优化频繁触发
let timerId: null | NodeJS.Timeout = null
const mouseMoveHandler = (e: MouseEvent) => {
//频繁触发的return出去
if (timerId != null) return
timerId = setTimeout(() => {
console.log({ x: e.clientX, y: e.clientY })
setPosition({ x: e.clientX, y: e.clientY })
//500后变为null
timerId = null
}, 500)
}
window.addEventListener('mousemove', mouseMoveHandler)
return () => window.removeEventListener('mousemove', mouseMoveHandler)
})
return (
<>
<p>位置:{JSON.stringify(position)}</p>
</>
)
}
const TestMouseInfo: React.FC = () => {
const [flag, setFlag] = useState(true)
return (
<>
<button onClick={() => setFlag((prev) => !prev)}>toggle</button>
{flag ? <Mouse /> : null}
</>
)
}
export default TestMouseInfo