使用初始状态来反应useState钩子事件处理程序

我仍然不停地做出反应,但仍在努力查看我在做什么错。我有一个用于调整面板大小的组件,边缘的onmousedown会更新状态的值,然后有一个用于mousemove的事件处理程序,该事件处理程序使用此值,但是在值更改后似乎没有更新。

这是我的代码:

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

回答:

useRef 阅读未来价值

当前,您的问题是您正在读取过去的价值。当您定义handleResize它属于该渲染时,因此,在重新渲染时,事件侦听器没有任何反应,因此它仍从其渲染中读取旧值。

要解决此问题,您应该使用一个ref并useRef保持更新,以便您可以读取当前值。

示例(链接到jsfiddle):

  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钩子事件处理程序 的全部内容, 来源链接: utcz.com/qa/409664.html

回到顶部