javascript - 我可以在 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挂钩中使用它吗?是否违反了钩子法则?
解决方案
推荐阅读
- php - Laravel 比较两个查询结果集
- sql - 在记录 Oracle 中显示空值
- php - 数组:如何实现这种数组
- vue.js - Vue:保持相同的消息,直到组件完全隐藏
- javascript - Chrome 扩展:从 background.js 获取变量到 popup.js
- apollo-client - Apollo 客户端 subscribeToMore 和 updateQuery 行为更新与新记录
- java - 使用 Intellij 加载 Gradle 项目时出错
- node.js - 将 socket.io 集成到 Restify API
- encoding - 什么类型的数据压缩涉及截断一段数据的前几位?
- c# - 将字符串放入 System.Data.DataTable 时将其转换为 DateTime