@td-design/rn-hooks
Version:
从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率
62 lines (58 loc) • 2.4 kB
JavaScript
;
var _tslib = require('../../_virtual/_tslib.js');
var react = require('react');
var lodashEs = require('lodash-es');
var useDebouncePlugin = function (fetchInstance, _a) {
var debounceWait = _a.debounceWait, debounceLeading = _a.debounceLeading, debounceTrailing = _a.debounceTrailing, debounceMaxWait = _a.debounceMaxWait;
var debounceRef = react.useRef();
var options = react.useMemo(function () {
var settings = {};
if (debounceLeading !== undefined) {
settings.leading = debounceLeading;
}
if (debounceTrailing !== undefined) {
settings.trailing = debounceTrailing;
}
if (debounceMaxWait !== undefined) {
settings.maxWait = debounceMaxWait;
}
return settings;
}, [debounceLeading, debounceTrailing, debounceMaxWait]);
react.useEffect(function () {
if (debounceWait) {
var originRunAsync_1 = fetchInstance.runAsync.bind(fetchInstance);
debounceRef.current = lodashEs.debounce(function (cb) {
cb();
}, debounceWait, 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 = debounceRef.current) === null || _a === void 0 ? void 0 : _a.call(debounceRef, function () {
originRunAsync_1.apply(void 0, _tslib.__spreadArray([], _tslib.__read(args), false)).then(resolve)
.catch(reject);
});
});
};
return function () {
var _a;
(_a = debounceRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
fetchInstance.runAsync = originRunAsync_1;
};
}
return function () { };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debounceWait, options]);
if (!debounceWait)
return {};
return {
onCancel: function () {
var _a;
(_a = debounceRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
},
};
};
exports.useDebouncePlugin = useDebouncePlugin;