使用初始状态来反应useState钩子事件处理程序 [英] React useState hook event handler using initial state
问题描述
我仍然不停地做出反应,但仍在努力查看我在这里做错了什么.我有一个用于调整面板大小的组件,在边缘的onmousedown上更新状态值,然后为mousemove使用事件处理程序,该事件处理程序使用该值,但是在值更改后似乎没有更新.
I'm still getting my head around react hooks but struggling to see what I'm doing wrong here. I have a component for resizing panels, onmousedown of an edge I update a value on state then have an event handler for mousemove which uses this value however it dosn't seem to be updating after the value has changed.
这是我的代码:
export default memo(() => {
const [activePoint, setActivePoint] = useState(null); // initial is null
const handleResize = () => {
console.log(activePoint); // is null but should be 'top|bottom|left|right'
};
const resizerMouseDown = (e, point) => {
setActivePoint(point); // setting state as 'top|bottom|left|right'
window.addEventListener('mousemove', handleResize);
window.addEventListener('mouseup', cleanup); // removed for clarity
};
return (
<div className="interfaceResizeHandler">
{resizePoints.map(point => (
<div
key={ point }
className={ `interfaceResizeHandler__resizer interfaceResizeHandler__resizer--${ point }` }
onMouseDown={ e => resizerMouseDown(e, point) }
/>
))}
</div>
);
});
问题出在handleResize
函数上,应该使用最新版本的activePoint
,它是字符串top|left|bottom|right
,而不是null
.
The problem is with the handleResize
function, this should be using the latest version of activePoint
which would be a string top|left|bottom|right
but instead is null
.
推荐答案
useRef
读取未来值
当前,您的问题是您正在读取过去的价值.定义handleResize
时,它属于该渲染,因此,重新渲染时,事件侦听器没有任何反应,因此它仍从其渲染中读取旧值.
useRef
to read future value
Currently, your issue is that you're reading a value from the past. When you define handleResize
it belongs to that render, therefore, when you rerender, nothing happens to the event listener so it still reads the old value from its render.
要解决此问题,您应该通过useRef
使用一个保持更新的引用,以便可以读取当前值.
To fix this, you should use a ref via useRef
that you keep updated so that you can read the current value.
const [activePoint, _setActivePoint] = React.useState(null);
// define a ref
const activePointRef = React.useRef(activePoint);
// in place of original `setActivePoint`
const setActivePoint = x => {
activePointRef.current = x; // keep updated
_setActivePoint(x);
};
const handleResize = () => {
// now when reading `activePointRef.current` you'll
// have access to the current state
console.log(activePointRef.current);
};
const resizerMouseDown = /* still the same */;
return /* return is still the same */
这篇关于使用初始状态来反应useState钩子事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!