All files / src/_util use-default.ts

100% Statements 8/8
66.67% Branches 4/6
66.67% Functions 2/3
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33    60x                       932x     932x 476x       456x     6x 6x 6x          
import { useState } from "react";
 
const noop = () => {};
 
export interface ChangeHandler<T, P extends any[]> {
  (value: T, ...args: P);
}
 
export function useDefault<T, P extends any[]>(
  value: T,
  defaultValue: T,
  onChange: ChangeHandler<T, P>
): [T, ChangeHandler<T, P>] {
  // 无论是否受控,都要 useState,因为 Hooks 是无条件的
  const [internalValue, setInternalValue] = useState(defaultValue);
 
  // 受控模式
  if (typeof value !== "undefined") {
    return [value, onChange || noop];
  }
 
  // 非受控模式
  return [
    internalValue,
    (newValue, ...args) => {
      setInternalValue(newValue);
      Eif (typeof onChange === "function") {
        onChange(newValue, ...args);
      }
    },
  ];
}