reactjs - 拖放滑块更新计数太快
问题描述
要更新幻灯片计数,我使用https://github.com/bokuweb/react-rnd使用拖放交互。我用作参考,滑动到达一定距离后调用方法的移动。问题在于,随着事件在达到该距离后被多次调用,计数会持续快速增长。
https://codesandbox.io/s/drag-drop-react-rnd-cm8x3上的完整演示
我尝试禁用拖放,但计数器增加得如此之快,以至于没有时间停止它。我也尝试将位置设置为开头,但它似乎只在用户释放点击(或手指)时更新。我也尝试过设置一个小距离但不起作用,因为如果你走得快,它就不会计算,或者如果你放慢速度,计数会继续快速增加。
type DraggableData = {
node: HTMLElement,
x: number,
y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number
};
dragin = (_e: MouseEvent, data: DraggableData ) => {
// @TODO: It should return to the starting position with the previous step
if (400 < data.x && data.x < 410) {
this.prevStep();
}
console.log(data.x);
// @TODO: It should return to the starting position with the next step
if (745 < data.x) {
// Needs to return to beginning!!!!
this.setState({
xPosition: 0,
yPosition: 0
});
// The code keeps executing a lot of times.
// Maybe create a variable that stores only the first time it hits
// or how can it be controlled?
console.log('next Step');
this.nextStep();
}
};
可以在https://codesandbox.io/s/drag-drop-react-rnd-cm8x3找到代码演示
向右移动时,幻灯片应该消失,然后下一张幻灯片出现在初始位置。
解决方案
终于找到了一个变通的解决方案。将项目用作状态并更新它不是一个好主意,因为如前所述,当达到条件时,它会更新并更新直到拖动停止。为避免最好将项目数组用作状态,一旦达到条件,使用 pop 或 shift 从数组中删除项目。
// Solution
nextStep = () => {
const { items } = this.state;
if (items.length === 1) {
this.setState({ isActive: false });
return;
}
const newItems = [...items];
newItems.pop();
this.setState(prevState => ({ items: newItems, step: prevState.step + 1 }));
};
// Old code with issues
nextStep = () => {
const { step } = this.state;
if (step === Items.length - 1) {
this.setState({ isActive: false, step: 0, item: Items[0] });
return;
}
this.setState(prevState => ({
step: prevState.step + 1,
item: Items[prevState.step + 1]
}));
};
可以在此处找到更新的解决方案:https ://codesandbox.io/s/drag-drop-react-draggable-6qi1j
推荐阅读
- python - 覆盖继承的属性设置器(不带 fset)
- ios - 运行时的 swift_unexpectedError 到底是什么?
- palantir-foundry - Foundry 数据连接是否支持 SFTP 源?
- python - 如何在Python的嵌套字典中获取具有相同键的所有值?
- node.js - 如果文档没有被任何其他文档引用,如何从集合中删除文档
- python - 使用拆包时如何知道退货中的代码更改
- android - Flutter:如何控制相互冲突的手势?
- visual-studio-code - VimPlugin 光标在单击时不更新位置
- python-3.x - 如何正确调用 AWS Lambda + API Gateway 的 queryStringParameters?
- python - InvalidArgumentException:消息:二进制不是使用 GeckoDriver Firefox Selenium 和 Python 的 Firefox 可执行错误