@td-design/rn-hooks
Version:
从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率
55 lines (52 loc) • 2.14 kB
JavaScript
import { __spreadArray, __read } from '../../_virtual/_tslib.js';
import { useRef, useMemo, useEffect } from 'react';
import { throttle } from 'lodash-es';
var useThrottlePlugin = function (fetchInstance, _a) {
var throttleWait = _a.throttleWait, throttleLeading = _a.throttleLeading, throttleTrailing = _a.throttleTrailing;
var throttleRef = useRef();
var options = useMemo(function () {
var settings = {};
if (throttleLeading !== undefined) {
settings.leading = throttleLeading;
}
if (throttleTrailing !== undefined) {
settings.trailing = throttleTrailing;
}
return settings;
}, [throttleLeading, throttleTrailing]);
useEffect(function () {
if (throttleWait) {
var originRunAsync_1 = fetchInstance.runAsync.bind(fetchInstance);
throttleRef.current = throttle(function (cb) {
cb();
}, throttleWait, options);
fetchInstance.runAsync = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new Promise(function (resolve, reject) {
var _a;
(_a = throttleRef.current) === null || _a === void 0 ? void 0 : _a.call(throttleRef, function () {
originRunAsync_1.apply(void 0, __spreadArray([], __read(args), false)).then(resolve)
.catch(reject);
});
});
};
return function () {
var _a;
fetchInstance.runAsync = originRunAsync_1;
(_a = throttleRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
};
}
}, [throttleWait, throttleLeading, throttleTrailing]);
if (!throttleWait)
return {};
return {
onCancel: function () {
var _a;
(_a = throttleRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
},
};
};
export { useThrottlePlugin };