代码如下
const noop = () => undefined;
const useEffectRef = callback => {
const disposeRef = useRef(noop);
const effect = useCallback(
element => {
disposeRef.current();
// 确保这货只被调用一次,所以调用完就干掉
disposeRef.current = noop;
if (element) {
const dispose = callback(element);
if (typeof dispose === 'function') {
disposeRef.current = dispose;
}
else if (dispose !== undefined) {
console.warn('Effect ref callback must return undefined or a dispose function');
}
}
},
[callback]
);
return effect;
};
const Foo = ({visible, text}) => {
const colorful = useCallback(
element => {
const tick = setInterval(
() => {
// 循环取下一个字符变色
},
1000
);
return () => clearInterval(tick);
},
[]
);
const ref = useEffectRef(colorful);
return visible ? <span ref={ref}>{text}</span> : null;
};
精简代码如下
简化了下,感觉类似于这个套路,
数接受一个函数,可以在不改变函数内部代码的情况下,加一些额外处理,比如打印日志啊,延迟执行啊 等等
如果硬要扯上设计模式的话,姑且叫 装饰器 或者 面向切面吧 😁