【发布时间】:2019-08-11 09:53:28
【问题描述】:
我仍然在思考反应钩子,但很难看出我在这里做错了什么。我有一个用于调整面板大小的组件,边缘的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。
【问题讨论】:
-
如果你做
console.log(point),点的价值是多少,就在setActivePoint(point)之上。我想知道resizerMouseDown它是否被调用了。 -
您的
.addEventListener(调用似乎正在使用该渲染中的当前函数,因此,当您更改activePoint并重新渲染时,这些事件侦听器不会更新为指向新的activePoint
标签: javascript reactjs ecmascript-6 react-hooks