Skip to content

Commit

Permalink
fix: 修复钩子的逻辑错误
Browse files Browse the repository at this point in the history
使用isUncontrolledRef判断组件是否处于非受控状态 避免因上级组件更新而导致结果错误
更新测试用例
  • Loading branch information
FanetheDivine committed Aug 6, 2024
1 parent 8bc4086 commit 3d87de4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
11 changes: 11 additions & 0 deletions packages/hooks/src/useValueMutation/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ describe('useMutableValue', () => {
expect(hook.result.current[0]).toBe(newValue);
});

it('test repeat call with the same value', () => {
const hook = setUp('test', () => {});
const [, onChange] = hook.result.current;
act(() => onChange('new value'));
const newValue = 'new value1';
hook.rerender([newValue, () => {}]);
expect(hook.result.current[0]).toBe(newValue);
hook.rerender([newValue, () => {}]);
expect(hook.result.current[0]).toBe(newValue);
});

it('onChange should be called', () => {
const testOnChange = jest.fn();
const hook = setUp('test', testOnChange);
Expand Down
7 changes: 6 additions & 1 deletion packages/hooks/src/useValueMutation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ function useValueMutation<T, V>(
) {
const prevValueRef = useRef(value);
const [changedValue, setChangedValue] = useState<T>(value);
const isUncontrolledRef = useRef(false);
const onInnerChange = useMemoizedFn((newVal: T) => {
isUncontrolledRef.current = true;
setChangedValue(newVal);
return onChange(newVal);
});
const equal = isEqual(prevValueRef.current, value) || isEqual(value, changedValue);
const curValue = equal ? changedValue : value;
if (!equal) {
isUncontrolledRef.current = false;
}
const curValue = isUncontrolledRef.current ? changedValue : value;

prevValueRef.current = value;
return [curValue, onInnerChange] as const;
Expand Down

0 comments on commit 3d87de4

Please sign in to comment.