我可以在 React/Preact 中为 useEffect 钩子使用动态选择的函数吗?

问题描述

我正在构建一个复杂的动画钩子序列。动画的选择取决于钩子接收到的 props。传统上,我会使用单个 useEffect,然后通过在依赖项数组中声明所有使用的依赖项来完成其中的所有操作。

然而,这使得整体效果非常笨拙。我想将该效果拆分为多个较小的函数,其中每个函数都有自己的依赖项列表。我可以在 Preact/React 中执行此操作,因为我正在执行以下操作:

import { useEffect } from 'preact/hooks';


function makeEffect1([anchor]) {
  return () => {
    // Animation type 1

    return () => {
      /* Cleanup effect */
    };
  };
}


function makeEffect2([anchor,popper]) {
  return () => {
    // Animation type 2

    return () => {
      /* Cleanup effect */
    };
  };
}


function makeEffect3([anchor,popper,followWidth]) {
  return () => {
    // Animation type 3

    return () => {
      /* Cleanup effect */
    };
  };
}


function useMyEffect(type,opts) {

  const deps = type === 1
    ? [opts.anchor]
    : type === 2
      ? [opts.anchor,opts.popper]
      : [opts.anchor,opts.popper,opts.followWidth];

  const effectToUse = type === 1
    ? makeEffect1(deps)
    : type === 2 ? makeEffect2(deps) : makeEffect3(deps);

  useEffect(effectToUse,deps);
}

我可以使用动态选择的函数及其动态依赖项列表(它可以跨重新呈现可变大小的列表),然后在对 useEffect 钩子的实际调用中使用它吗?是否违反了钩子定律?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)