use-state-track-prop
Version:
A react hook for private state of component tracking some props
115 lines (95 loc) • 3.18 kB
JavaScript
/**
* Bundle of use-state-track-prop
* Generated: 2023-09-26
* Version: 1.3.1
* License: MIT
* Author: 2631541504@qq.com
*/
import { useRef, useReducer, useState, useCallback } from 'react';
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
/**
* @param props 组件的 prop 的集合
* 如果 props 为引用类型,为了提高性能,请使用 useMemo 来生成
*
* Assembly of the prop of the component
* If props is a reference type, use `useMemo` hook to generate it for performance
*
* @param mapPropToState 映射函数
*
* map function
*
* @return [state, setState]
* */
function useStateTrackProp(props, mapPropToState) {
var preProps = useRef();
var map = useRef();
map.current = mapPropToState || function ($prop) {
return $prop;
};
var _useReducer = useReducer(function (pre) {
return pre + 1;
}, 0),
_useReducer2 = _slicedToArray(_useReducer, 2),
forceUpdate = _useReducer2[1];
var initState = useState(function () {
return map.current(props);
})[0];
var state = useRef(initState);
if (props !== preProps.current) {
// Update
state.current = map.current(props, state.current, preProps.current);
preProps.current = props;
}
return [state.current, // setState method
useCallback(function (action) {
state.current = typeof action === 'function' ? action(state.current) : action;
forceUpdate();
}, [forceUpdate])];
}
export default useStateTrackProp;