UNPKG

rc-hooks

Version:
38 lines (37 loc) 1.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var react_1 = require("react"); /** * 管理 object 类型 state 的 Hook ,用法和 class 组件的 `this.setState` 基本一致,内部使用展开操作符进行合并。 * * @param {Object} initialValue 初始值。 * @returns * @example * const [state, setState] = useSetState({ * foo: 0, * count: 0, * bar: undefined as string | undefined * }); * * // 单独更新某个状态,不影响其他状态值 * setState({ * foo: 1 * }); * * useEffect(()=>{ * console.log(state); * // { foo: 1, count: 0, bar: undefined } * }, [state]); */ function useSetState(initialValue) { var _a = tslib_1.__read((0, react_1.useState)(initialValue), 2), state = _a[0], setState = _a[1]; var set = (0, react_1.useCallback)(function (nextState) { setState(function (prevState) { var newState = nextState instanceof Function ? nextState(prevState) : nextState; return newState instanceof Object ? tslib_1.__assign(tslib_1.__assign({}, prevState), newState) : prevState; }); }, []); return [state, set]; } exports.default = useSetState;