我在mousemove
中有componentDidMount
个事件,我想每帧只调用setState()
一次以更新DOM。
怎么做?
答案 0 :(得分:1)
不确定你的意思是“每帧一次”,但我可以想象你不想重新渲染每个像素鼠标移动。
您可以做的是在状态中保存时间戳和/或鼠标位置,如果超过x时间或超过x像素的鼠标移动,则只保存setState。像这样:
onMouseMove(mouseX, mouseY) {
// check if more than 1 second has elapsed or if mouse has moved more than 10 pixels
let timestamp = Date.now()
if (
(timestamp - this.state.now > 1000) ||
(Math.abs(mouseX - this.state.mouseX) > 10) ||
(Math.abs(mouseY - this.state.mouseY) > 10) {
// store the new timestamp + mouse position in state, which will trigger re-render
this.setState({
now: timestamp,
mouseX: mouseX,
mouseY: mouseY
})
}
}