首页 > 解决方案 > 我可以在 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挂钩中使用它吗?是否违反了钩子法则?

标签: javascriptreactjsreact-hookspreact

解决方案


推荐阅读