@td-design/rn-hooks
Version:
从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率
57 lines (53 loc) • 2.17 kB
JavaScript
;
var _tslib = require('../../_virtual/_tslib.js');
var react = require('react');
var lodashEs = require('lodash-es');
var useThrottlePlugin = function (fetchInstance, _a) {
var throttleWait = _a.throttleWait, throttleLeading = _a.throttleLeading, throttleTrailing = _a.throttleTrailing;
var throttleRef = react.useRef();
var options = react.useMemo(function () {
var settings = {};
if (throttleLeading !== undefined) {
settings.leading = throttleLeading;
}
if (throttleTrailing !== undefined) {
settings.trailing = throttleTrailing;
}
return settings;
}, [throttleLeading, throttleTrailing]);
react.useEffect(function () {
if (throttleWait) {
var originRunAsync_1 = fetchInstance.runAsync.bind(fetchInstance);
throttleRef.current = lodashEs.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, _tslib.__spreadArray([], _tslib.__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();
},
};
};
exports.useThrottlePlugin = useThrottlePlugin;