UNPKG

rc-hooks

Version:
36 lines (35 loc) 1.12 kB
import { __assign, __read } from "tslib"; import { useState, useCallback } from '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 = __read(useState(initialValue), 2), state = _a[0], setState = _a[1]; var set = useCallback(function (nextState) { setState(function (prevState) { var newState = nextState instanceof Function ? nextState(prevState) : nextState; return newState instanceof Object ? __assign(__assign({}, prevState), newState) : prevState; }); }, []); return [state, set]; } export default useSetState;