跳到主要内容

useCustomCompareEffect

修改后的 useEffect,它接受一个比较函数,用于比较依赖项而不是引用相等性

Usage

实时编辑器

function Demo() {
  const [person, setPerson] = useState({ name: "bob", id: 1 });
  const [count, setCount] = useState(0);
  useCustomCompareEffect(
    () => {
      setCount(c => c + 1);
    },
    [person],
    (prevDeps, nextDeps) => prevDeps[0].id === nextDeps[0].id,
  );

  return (
    <div>
      <button
        onClick={() => {
          setPerson({ name: "joey", id: 1 });
        }}
      >
        Change Person Name
      </button>
      <button
        onClick={() => {
          setPerson({ name: "bob", id: 2 });
        }}
      >
        Change Person Id
      </button>
      <p>useCustomCompareEffect with deep comparison: {count}</p>
    </div>
  );
};

结果
Loading...

API

useCustomCompareEffect

Returns

void

Arguments

参数名描述类型默认值
effect副作用函数React.EffectCallback (必填)-
deps依赖列表TDeps (必填)-
depsEqual依赖比较函数DepsEqualFnType<TDeps> (必填)-

DepsEqualFnType

export type DepsEqualFnType<TDeps extends DependencyList> = (prevDeps: TDeps, nextDeps: TDeps) => boolean;