Skip to content

Commit

Permalink
修复 useDrag 闭包问题 (#1838)
Browse files Browse the repository at this point in the history
* fix: data closure problem

* fix: eslint warn

* feat: add test
  • Loading branch information
hchlq authored Sep 2, 2022
1 parent 4033639 commit a902010
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
21 changes: 15 additions & 6 deletions packages/hooks/src/useDrag/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { renderHook } from '@testing-library/react-hooks';
import useDrag, { Options } from '../index';
import type { Options } from '../index';
import useDrag from '../index';
import type { BasicTarget } from '../../utils/domTarget';

const setup = <T>(data: T, target: BasicTarget, options?: Options) =>
renderHook(() => useDrag(data, target, options));
renderHook((newData: T) => useDrag(newData ? newData : data, target, options));

const events = {};
const events: Record<string, (event: any) => void> = {};
const mockTarget = {
addEventListener: jest.fn((event, callback) => {
events[event] = callback;
Expand Down Expand Up @@ -35,14 +36,22 @@ describe('useDrag', () => {
setData: jest.fn(),
},
};
setup(1, mockTarget as any, {
const hook = setup(1, mockTarget as any, {
onDragStart,
onDragEnd,
});
events['dragstart'](mockEvent);
events.dragstart(mockEvent);
expect(onDragStart).toBeCalled();
expect(mockEvent.dataTransfer.setData).toBeCalledWith('custom', '1');
events['dragend'](mockEvent);
events.dragend(mockEvent);
expect(onDragEnd).toBeCalled();

hook.rerender(2);

events.dragstart(mockEvent);
expect(onDragStart).toBeCalled();
expect(mockEvent.dataTransfer.setData).toHaveBeenLastCalledWith('custom', '2');
events.dragend(mockEvent);
expect(onDragEnd).toBeCalled();
});

Expand Down
4 changes: 2 additions & 2 deletions packages/hooks/src/useDrag/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface Options {

const useDrag = <T>(data: T, target: BasicTarget, options: Options = {}) => {
const optionsRef = useLatest(options);

const dataRef = useLatest(data);
useEffectWithTarget(
() => {
const targetElement = getTargetElement(target);
Expand All @@ -20,7 +20,7 @@ const useDrag = <T>(data: T, target: BasicTarget, options: Options = {}) => {

const onDragStart = (event: React.DragEvent) => {
optionsRef.current.onDragStart?.(event);
event.dataTransfer.setData('custom', JSON.stringify(data));
event.dataTransfer.setData('custom', JSON.stringify(dataRef.current));
};

const onDragEnd = (event: React.DragEvent) => {
Expand Down

0 comments on commit a902010

Please sign in to comment.